python类学习

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'
>>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值