
类(Class)和实例(Instance)是面向对象最重要的概念。
类是指抽象出的模板。实例则是根据类创建出来的具体的“对象”,每个对象都拥有从类中继承的相同的方法,但各自的数据可能不同。
在python中定义一个类:
1 2 | class Student(object):
pass
|
关键字class后面跟着类名,类名通常是大写字母开头的单词,紧接着是(object),表示该类是从哪个类继承下来的。通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承下来的类。
定义好了 类,就可以根据Student类创建实例:
1 2 3 4 5 6 7 8 | >>> class Student(object):
... pass
...
>>> bart = Student() # bart是Student()的实例
>>> bart
< __main__.Student object at 0x101be77f0>
>>> Student # Student 本身是一个类
< class '__main__.Student'>
|
可以自由地给一个实例变量绑定属性,比如,给实例bart绑定一个name属性:
1 2 | >>> bart.name = "diggzhang"
>>> bart.name'diggzhang'
|
类同时也可以起到模板的作用,我们可以在创建一个类的时候,把一些认为公共的东西写进类定义中去,在python中通过一个特殊的__init__方法实现:
1 2 3 4 5 | class Student(object):
"""__init__ sample."""
def __init__(self, name, score):
self.name = name
self.score = score
|
__init__方法的第一个参数永远都是self,表示创建实例本身,在__init__方法内部,可以把各种属性绑定到self,因为self指向创建的实例本身。
有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去。如下面的类,在新建实例的时候,需要把name和score属性捆绑上去:
1 2 3 4 5 | class Student(object):
"""example for __init__ function passin args."""
def __init__(self, name, score):
self.name = name
self.score = score
|
我们直接看个实例,如果我们老老实实传name和score进去的时候,成功声明了这个实例,但是只传一个值的时候,报错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | In [1]: class Student(object):
...: def __init__(self, name, score):
...: self.name = name
...: self.score = score
...:
In [2]: bart = Student('diggzhang', 99)
In [3]: bart.name
Out[3]: 'diggzhang'
In [4]: bart.score
Out[4]: 99
In [5]: bart_test = Student('max')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
< ipython-input-6-97f4e2f67951 > in < module >()
----> 1 bart_test = Student('max')
TypeError: __init__() takes exactly 3 arguments (2 given)
|
更多学习内容,请点击Python学习网。