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

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

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1537202/variables-inside-and-outside-of-a-class-init-function\">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.

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

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