__metaclass__=type
#特殊方法,属性,迭代器
#特殊方法:eg.__init__和一些处理对象访问的方法,允许你创建自己的序列或者映射
#属性:旧版本的python通过特殊方法处理,新版本的用property函数处理
#迭代器:使用特殊方法__iter__在for循环中使用
#-------------------------------------------------------------------------------
#构造方法:__init__
class FoolBar:
def __init__(self,value=42):
self.somevar=value
f=FoolBar()
print(f.somevar)
f=FoolBar('This is a constructor argument')
print(f.somevar)
#析构方法:__del__.在对象就要被垃圾回收之前调用,发生调用的时间不可知,尽量避免使用
#-------------------------------------------------------------------------------
#重写基类(超类)的一般方法以及构造方法
class A:
def hello(self):
print('Hello,I\'m A')
class B(A):
pass
class C(A):
def hello(self):
#重写类A的方法
print('Hello,I\'m C')
a=A()
b=B()
c=C()
a.hello()
#B继承超类(基类)A,B类没有hello()方法。B类对象调用hello()方法,先在B类中查找,如果没有找到,
#就去基类A中查找。
b.hello()
c.hello()
class Bird:
def __init__(self):
self.hungry=True
def eat(self):
if self.hungry:
print('Aaaah need food...')
self.hungry=False
else:
print('No thanks!')
class SongBird1(Bird):
#构造方法被重写,新的构造方法没有任何关于初始化hungry的特性
#如果想要调用基类的eat(),必须调用其基类的构造方法确保进行基本的初始化,两种方式:
# 调用基类构造方法的未绑定版本
# 使用super函数
def __init__(self):
self.sound='Squawk!'
def sing(self):
print(self.sound)
class SongBird2(Bird):
def __init__(self):
#绑定方法:调用一个实例的方法,该方法的self参数会被自动绑定到实例上
#未绑定方法:直接调用类的方法(eg.Bird.__init__(self)),没有实例被绑定,可以自由的提供需要的self参数
#通过将当前的实例作为self参数传递给基类的构造方法,使得当前实例具有基类的所有属性
Bird.__init__(self)
self.sound='Squawk!'
def sing(self):
print(self.sound)
try:
sb1=SongBird1()
sb1.sing()
sb1.eat()
except AttributeError:
print('No hungry attribute...')
sb2=SongBird2()
sb2.sing()
sb2.eat()
输出:
42
This is a constructor argument
Hello,I'm A
Hello,I'm A
Hello,I'm C
Squawk!
No hungry attribute...
Squawk!
Aaaah need food...
#使用Super函数
__metaclass__=type
class Bird:
def __init__(self):
self.hungry=True
def eat(self):
if self.hungry:
print('Aaaah need food...')
self.hungry=False
else:
print('No thanks!')
class SongBird(Bird):
def __init__(self):
#super函数返回一个super对象,负责进行方法解析:查找所有超类,直到找到所需的特性为止
super(SongBird,self).__init__()
self.sound='Squawk!'
def sing(self):
print(self.sound)
sb=SongBird()
sb.sing()
sb.eat()
sb.eat()
输出:
Squawk!
Aaaah need food...
No thanks!