[Dynamic Language] Python 静态方法、类方法、属性

突然发现Python属性是比较有意思的,属性是继承的,先看下面代码:

38 class ABeen(object):
39 def f(self):
40 return "abeen"
41 g = property(f)
42
43 class Shan(ABeen):
44 def f(self):
45 return "shanshan"
46
47 s = Shan()
48 print s.g

out: abeen
是不是和你想象的不一样呢?

  其实g属性是在ABeen类语句执行的时候,通过传递函数对象f创建的,虽然Shan类语句在执行的时候重新定义了函数f,

但这与属性无关,因为属性不执行对这个名称的查找,而是使用在创建时使用的函数对象。

要实现我们想象中的行为,可以借"猪"一个中间层来实现,下面 getf 就是我们借的“猪”了 哈哈!

  4 class ABeen(object):
5 def f(self):
6 return "abeen"
7
8 def getf(self):
9 return self.f()
10
11 g = property(getf)
12
13 class Shan(ABeen):
14 def f(self):
15 return "shanshan"
16
17 s = Shan()
18 print s.g

静态方法

  4 class AClass(object):
5 def astatic():
6 print "a static method by abeen shanshan"
7
8 astatic = staticmethod(astatic)
9
 
10 class BClass(AClass):
11 pass

14 o = AClass()
15 o.astatic()
16 AClass.astatic()
17
18 b = BClass()
19 b.astatic()

类方法

22 class ATest(object):
23 def aclassmethod(cls):
24 print 'a class method for ', cls.__name__
25 aclassmethod = classmethod(aclassmethod)
26
27 class BTest(ATest):
28 pass
29
32 t = ATest()
33 t.aclassmethod()
34 ATest.aclassmethod()
35
36 bt = BTest()
37 bt.aclassmethod()
38 BTest.aclassmethod()

静态方法和类方法,也可以如下更简单的方式实现(在方面前面加@staticmethod/classmethod)

实际上就是个装饰器

4 class AClass(object):
5 def astatic():
6 print "a static method by abeen shanshan"
7 astatic = staticmethod(astatic)
8
9 @staticmethod
10 def bstatic():
11 print "b static method by abeen shanshan"

26 class ATest(object):
27 def aclassmethod(cls):
28 print 'a class method for ', cls.__name__
29 aclassmethod = classmethod(aclassmethod)
30
31 @classmethod
32 def bclassmethod(self):
33 print "b classmethod "

posted @ 2011-01-13 23:18  ABeen  阅读(747)  评论(0编辑  收藏  举报