我注意到,在Python中,人们用两种不同的方式初始化类属性。
第一种方式是这样的:
class MyClass:
__element1 = 123
__element2 = "this is Africa"
def __init__(self):
#pass or something else
另一个样式是这样的:
class MyClass:
def __init__(self):
self.__element1 = 123
self.__element2 = "this is Africa"
初始化类属性的正确方法是什么?
两种方法都不一定正确或不正确,它们只是两种不同的类元素:
__init__方法之外的元素是静态元素;他们属于这个阶层。
__init__方法中的元素是对象(self)的元素;他们不属于这个阶层。
你可以用一些代码更清楚地看到它:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
如您所见,当我们改变class元素时,它对两个对象都发生了改变。但是,当我们改变object元素时,其他对象保持不变。
两种方法都不一定正确或不正确,它们只是两种不同的类元素:
__init__方法之外的元素是静态元素;他们属于这个阶层。
__init__方法中的元素是对象(self)的元素;他们不属于这个阶层。
你可以用一些代码更清楚地看到它:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
如您所见,当我们改变class元素时,它对两个对象都发生了改变。但是,当我们改变object元素时,其他对象保持不变。
我认为这个例子解释了风格之间的差异:
james@bodacious-wired:~$cat test.py
#!/usr/bin/env python
class MyClass:
element1 = "Hello"
def __init__(self):
self.element2 = "World"
obj = MyClass()
print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
File "./test.py", line 17, in <module>
print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'
Element1绑定到类,element2绑定到类的一个实例。