python学习—Day16—类(一般形式、继承)

来源:互联网 发布:时时彩做计划软件 编辑:程序博客网 时间:2024/05/17 18:15

类的一般形式:

创建类使用class关键字,class后面跟类名字,可以自定义,最后以冒号结尾。可以使用三引号来备注类的说明

class ren(object):\\所有创建的类都是继承于object的    name = "meizi"    age =  "18"    def hello(self):\\self:默认格式,代表函数本身        print ("hello ladygirl")a = ren()print(type(a))print (a.name)a.hello()
<class '__main__.ren'>

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'hello', 'name']
meizi
hello ladygirl

class ren():    name = "meizi"    age =  "18"    def hello(self):        print ("hello ladygirl")a = ren()print(type(a))print(dir(a))print (a.name)a.hello()
<type 'instance'> \\没有object,属性不再是class,但是貌似并不影响使用?
['__doc__', '__module__', 'age', 'hello', 'name']
meizi
hello ladygirl


类的构造器:创建类的时候的规范写法,写好构造器,之后调用类会用到

__init__构造函数,在生成对象时调用,由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去,通过定义一个特殊的__init__方法,在创建实例的时候就把name等属性绑定上去。

class ren(object):    def __init__(self, name, sex): \\这里定义类的构造器,调用类时则必须读取init进行初始化。        self.name = name        self.sex = sex    def hello(self):        print('hello {0}'.format(self.name))# test = ren('xiaojingjing', 'W')\\这里的参数是构造器定义好的,使用则必须有两个参数,否则报错# test.hello()ren('xiaojingjing', 'W').hello()
hello xiaojingjing

注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因此self就指向创建的实例本身。

有了__init__方法,在创建实例的时候,就不能传空的参数了。必须传入与__init__方法匹配的参数,但是self不需要传,python解释器会自己把实例变量传进去。


类的继承:

class A(object):    passclass B(A):\\B继承了A的方法    pass
如果类A中有B需要的方法等,可以使用类的继承直接调用,而不需要再写一遍,直接写其他的方法。并且当调用方法时,是先在B中找,没有再去A里面找。

class A(object):    passclass B(object):    passclass C(A, B):    pass
这是类的多继承:同时继承A,B的方法(这是JAVA中不支持的)

注意事项:

1)在继承中类的构造(__init__()方法)不会自动调用,它需要在子类的构造中亲自调用。

2)python总是首先子类的方法,如果子类中没有找到,才会去父类中查找

示例:

class parent():    name = 'parent'    age = 200    def __init__(self):        print('my name is {0}'.format(self.name))    def get_name(self):        return self.name    def get_age(self):        return self.ageclass child(parent):    # name = 'child'     age = 20    def __init__(self):        print ('my name is {0}'.format(self.name))    def hello(self):        print('hello world')a = child()a.hello()print(a.get_name())
my name is parent
hello world
parent







原创粉丝点击