1.类的一般形式
类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
一般用class关键字来创建一个类,class后面跟类名字,可以自定义,最后以冒号结尾
class ClassName:
'''类的说明'''
类的内容
类的内容可以写类的全局变量等:
案例:
class man(object): #object默认是所有类的父类,不写默认继承object
"""this is a class"""
name = 'zk'
age = 30
a = man() # 就是把 类man实例化
print (type(a))
print(a.name)
print(a.age)
a.age = 20
print(a.age)
返回的结果为:
<class '__main__.man'>
zk
30
20
#调用类的方法和变量,直接实例化类的后面直接用“.”调用
#如果想给实例a添加变量或者赋值,可以直接用“.”加变量赋值
2.类的构造器
init
__init__ 构造函数,在生成对象时调用。
构造方法init的使用:
class student(object):
def __init__(self,name,score):
self.name = name
self.score = score
s = student('kk',90)
print (s.name)
print (s.score)
结果是:
kk
90
#
在传递参数的时候,必须是传递两个参数,
name
和
score
,不然报错
# Self 的参数不用传递, python 自动会把 Student 实例化的 s 传递给第一个参数,即 self
3.类的继承
继承类的格式:
class A(父类):
…
多继承
class A: # 定义类 A
.....
class B: # 定义类 B
.....
class C(A, B): # 继承类 A 和 B
.....
多继承其实在需要在父类的位置,直接写多个父类就可以,然后用“,”分开就可以了,C类就同时继承了A类和B类。
Python类的继承注意事项:
1. 在继承中类的构造(__init()方法)不会自动调用,它需要在子类的构造中亲自调用。
2. Python总是首先子类中的方法,如果子类没有找到,才回去父类中查找。
案例:class parent:
name = 'parent'
age = 100
def __init__(self):
print 'my name is parent'
def get_name(self):
return self.name
def get_age(self):
return self.age
class child(parent):
def __init__(self):
print 'I am a child'
def hello(self):
print 'hello,child'
a = child()
a.hello()
print (a.age)
print (a.name)
返回的结果:
I am a child
hello,child
100
parent
如果子类没有定义__init__()方法,子类初始化的时候就会调用父类的方法,但是当子类定义了__init__()方法,子类就不会调用父类的__init__()方法,那如果子类想实现父类构造器中的方法,然后自己在写自己特殊的方法呢,这样该怎么办呢?
用super()class parent(object):
name = 'parent'
age = 100
def __init__(self):
print 'my name is parent'
def get_name(self):
return self.name
def get_age(self):
return self.age
class child(parent):
def __init__(self):
super(child, self).__init__()
print ('I am a child')
def hello(self):
print 'hello child'
a = child()
a.hello()
print (a.age)
print (a.name)
返回的结果:
my name is parent
I am a child
hello child
100
parent
#这里在class parent(object):定义父类的时候,一定要写继承object类,不然那就会有如下的报错信息:TypeError: super() argument 1 must be type, not classobj,增加parent(object)就可以轻松解决。