可能重复:
Variables inside and outside of a class __init__() function
我注意到在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"
初始化类属性的正确方法是什么?
答案 0 :(得分:485)
这两种方式都不一定正确或不正确,它们只是两种不同的类元素:
__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元素时,它对两个对象都进行了更改。但是,当我们更改了对象元素时,另一个对象保持不变。
答案 1 :(得分:14)
我认为这个样本解释了样式之间的区别:
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绑定到类的实例。