参考:类和实例
注意理解第七点。
NOTE:
1.类是抽象的模板,比如Student类,实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。
一个是抽象模板,一个是具体实例。
class Student(object)
pass
Hint: Python中继承的方式 => 在类名之后加上([继承的类名])
。
上述Student类继承于object类,这个是所有的类最终都会继承的类。
2.创建实例是通过类名+()实现的。
如果有__init__()
构造函数,需要传入对应的参数,如:
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
注意:特殊方法“init”前后有两个下划线!!!
外界调用Student类创建对象时默认调用构造函数__init__(), 需要传入name和score参数。
bart = Student('Bart Simpson', 59)
3.__init__方法的第一个参数永远是self,表示创建的实例本身.
4.有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数。
5.和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且调用时,不用传递该参数。
6.数据封装:
在上面的Student类中,每个实例就拥有各自的name和score这些数据。要访问这些数据,就没有必要从外面的函数去访问,可以直接在Student类的内部定义访问数据的函数。称为“数据封装”。
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def PrintINFO(self):
print(self.name)
print(self.score)
数据和逻辑被“封装”起来了,调用很容易,但却不用知道内部实现的细节。
外部无需得知内部细节,只需要了解这个对象拥有的函数接口即可调用该对象的方法以实现某些功能。
7.和静态语言不同,Python允许对实例变量绑定任何数据,也就是说,对于两个实例变量,虽然它们都是同一个类的不同实例,但拥有的变量名称都可能不同:
>>> bart = Student('Bart Simpson', 59)
>>> lisa = Student('Lisa Simpson', 87)
>>> bart.age = 8
>>> bart.age
8
>>> lisa.age
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'age'
注意:Student对象中初始化的时候只有name和score两个属性,也就是说在初始化的时候创建了两个同一模板的、拥有相同属性的对象,但是这些对象可以加入自己的东西(属性)。
比如:
class Man(object):
def __init__(self, name, age):
self.name = name
self.age = age
def fuck():
print('Sleep with my girlfriend')
def main():
I = Man('chen', 20)
You = Man('xx', 20)
I.havegirlfriend = True
if I.havegirlfriend == True:
fuck()
if You.havegirlfriend == True:
print('error')
Sleep with my girlfriend
Traceback (most recent call last):
File "./oop1.py", line 38, in <module>
main()
File "./oop1.py", line 34, in main
if You.havegirlfriend == True:
AttributeError: 'Man' object has no attribute 'havegirlfriend'
You没有havegirlfriend,解释器raise Error。
2017/2/23