在 Python 中定义类变量的正确方法 [英] correct way to define class variables in Python

查看:41
本文介绍了在 Python 中定义类变量的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到在 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

另一种样式如下:

class MyClass:
  def __init__(self):
    self.__element1 = 123
    self.__element2 = "this is Africa"

初始化类属性的正确方法是什么?

Which is the correct way to initialize class attributes?

推荐答案

两种方式都不一定正确或不正确,它们只是两种不同的类元素:

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • __init__ 方法之外的元素是静态元素;他们属于班级.
  • __init__ 方法中的元素是对象的元素(self);他们不属于这个班级.
  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

你会用一些代码更清楚地看到它:

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

如您所见,当我们更改 class 元素时,它对两个对象都发生了变化.但是,当我们更改对象元素时,另一个对象保持不变.

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.

这篇关于在 Python 中定义类变量的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆