|
1. 类属性,实例属性
>>> class MC:
x = 0
z = {1:1}
def __init__(self):
self.y = 1
>>> mc1 = MC()
>>> mc2 = MC()
// 可以通过类名或实例名来访问类属性
>>> mc1.x, mc2.x, MC.x
>>> (0, 0, 0)
// 不能通过类名来访问实例属性
>>> mc1.y, mc2.y
>>> (1, 1)
>>> MC.y
>>> class MC has no attribute 'y'
// 实例赋值操作会产生同名实例属性,并遮蔽类属性
>>> mc1.x += 1
>>> mc1.x, mc2.x, MC.x
>>> (1, 0, 0)
>>> del mc1.x
>>> mc1.x, mc2.x, MC.x
>>> (0, 0, 0)
// 当类属性是可变变量时,会出现下面现象
// 此时没有产生实例属性
>>> mc1.z[2]=2
>>> mc1.z
>>> mc1.x, mc2.x, MC.x
>>> ({1:1,2:2},{1:1,2:2},{1:1,2:2})
// 类属性的修改应使用类名,而不是属性名
>>> MC.x += 1
>>> mc1.x, mc2.x, MC.x
>>> (1, 1, 1)
2. 实例方法,类方法,静态方法
class A(object):
# 类实例方法
def foo(self, x):
print "executing foo(%s,%s)" % (self, x)
# 类方法
@classmethod
def class_foo(cls, x):
print "executing class_foo(%s,%s)" % (cls, x)
# 静态方法
@staticmethod
def static_foo(x):
print "executing static_foo(%s)" % (x)
>>> a = A()
>>> a.foo(1)
executing foo(<__main__.A object at 0x02A8C210>,1)
>>> a.class_foo(1)
executing class_foo(<class '__main__.A'>,1)
>>> A.class_foo(1)
executing class_foo(<class '__main__.A'>,1)
>>> a.static_foo(1)
executing static_foo(1)
>>> A.static_foo(1)
executing static_foo(1)
- 类方法和静态方法都可以被类和类实例调用,类实例方法仅可以被类实例调用
- 类方法的隐含调用参数是类,而类实例方法的隐含调用参数是类的实例,静态方法没有隐含调用参数
- 实例方法可以访问实例属性和类属性,类方法可以访问类属性,静态方法两者都不能访问
- 类方法更像是C++/java中静态方法, 而静态方法像是放在类名字空间中的一个函数
|
|
|