Python中定义类变量的正确方法
我注意到在 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"
初始化类属性的正确方法是什么?
I noticed that in Python, people initialize their class attributes in two different ways.
The first way is like this:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这两种方式都不一定正确或不正确,它们只是两种不同类型的类元素:
__init__
方法之外的元素是静态元素;他们属于班级。__init__
方法中的元素是对象的元素 (self
);他们不属于这个阶级。通过一些代码,您将更清楚地看到它:
如您所见,当我们更改类元素时,两个对象都发生了更改。但是,当我们更改对象元素时,另一个对象保持不变。
Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:
__init__
method are static elements; they belong to the class.__init__
method are elements of the object (self
); they don't belong to the class.You'll see it more clearly with some code:
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.
我认为这个示例解释了样式之间的区别:
element1 绑定到类,element2 绑定到类的实例。
I think this sample explains the difference between the styles:
element1 is bound to the class, element2 is bound to an instance of the class.