正确的方法来定义Python类变量
问题描述:
可能重复:结果
Variables里面的一类__init __之外()函数
我注意到,在Python中,人们在两种不同的方式初始化它们的类属性。
I noticed that in Python, people initialize their class attributes in two different ways.
第一种方法是这样的:
class MyClass:
__element1 = 123
__element2 = "this is Africa"
def __init__(self):
#pass or something else
其他的风格是这样的:
The other style looks like:
class MyClass:
def __init__(self):
self.__element1 = 123
self.__element2 = "this is Africa"
这是初始化类属性的正确方法是什么?
Which is the correct way to initialize class attributes?
答
这两种方式不正确或不正确的,它们只是两种不同类型的类元素:
Both ways aren't correct or incorrect, they are just two different kind of class elements:
- 在
__ __的init
方法之外的元素为静态元素,这意味着,他们属于类。 - 在
里面的元素__的init __
方法是对象的元素(自
),它们不属于类。
- Elements outside the
__init__
method are static elements, it means, they belong to the class. - Elements inside the
__init__
method are elements of the object (self
), they don't belong to the class.
您会用一些code更清楚地看到它:
You'll see it more clearly with some code:
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
正如你所看到的,当我们改变了类元素,它改变了两个对象。但是,当我们改变了对象元素,另一个对象保持不变。
As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.