首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python种学习

2012-12-28 
python类学习1.魔术方法__init__(相当于php中的__construct)(1) class Test:?? ?def __init__(self):??

python类学习

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

#!/usr/bin/env python# -*- coding:utf-8 -*-class MyDescriptor(object): def __init__(self): self.count=0 self.l=[] def __get__(self,obj,objtype): if obj not in self.l: self.l.append(obj) self.count=self.count+1 return self.count def __set__(self,obj,objtype): raise AttributeError, "unreadable attribute"class testDescriptor(object): count=MyDescriptor() def __init__(self): print("count:%03d"%self.count) self.ct=self.count print("Object %03d constructed"%self.ct) def __del__(self): print("Object %03d destroyed"%self.ct)
然后我们就可以去调用了:

In [2]: a=testDescriptor()
count:001

In [3]: a=testDescriptor()
count:002

In [4]: a=testDescriptor()
count:003

In [5]: b=testDescriptor()
count:004

可以看到,这样就实现了在不同实例中数据的共享。

但我这个想法是否正确呢?

热点排行