1.魔术方法__init__(相当于php中的__construct)
(1)
>>> class Test:
def __init__(self):
self.var=34
>>> f=Test()
>>> f.var
34
(2)
>>> class Test:
def __init__(self,name='4nail'):
self.name=name
>>> f=Test()
>>> f.name
'4nail'
>>> f=Test('this is a init')
>>> f.name
'this is a init'
>>>
2.继承(inherite),B继承A
>>> class A:
def getClassName(self):
print 'Hello,I am A'
>>> class B(A):
pass
>>> a=A()
>>> b=B()
>>> a.getClassName()
Hello,I am A
>>> b.getClassName()
Hello,I am A
>>>
3.方法的覆盖
(1)
>>> class B:
def getClassName(self):
print 'Hello,I am B'
>>> a=A()
>>> b=B()
>>> a.getClassName()
Hello,I am A
>>> b.getClassName()
Hello,I am B
>>>
(2)出错,因为父类构造方法被覆盖了,所以会出错
>>> class Emploee:
def __init__(self):
self.name='wang'
>>> class Developer(Emploee):
def __init__(self):
self.age=23
def getAge(self):
print self.age
>>> a.name
'wang'
>>> b=Developer()
>>> b.age
23
>>> b.name
Traceback (most recent call last):
File "<pyshell#96>", line 1, in <module>
b.name
AttributeError: Developer instance has no attribute 'name'
>>>
(3)
解决(2)方法
>>> class Developer(Emploee):
def __init__(self):
Emploee.__init__(self)#调用父类构造方法
self.age=34
def getAge(self):
return self.age
>>> a=Emploee()
>>> b=Developer()
>>> a.name
'wang'
>>> b.age
34
>>> b.name
'wang'
>>>
python类学习
最新推荐文章于 2023-11-09 10:31:26 发布