【问题标题】:Working with class variable in Python 3.x在 Python 3.x 中使用类变量
【发布时间】:2020-10-18 07:31:39
【问题描述】:

我有一个关于 Python 类和变量的小问题。

为什么'self'关键字'破坏'第一个示例中的计数器变量的工作,而在第二个示例中(在机制方面与第一个非常相似)'self'关键字在结果条款:

# Counter does not work properly (incrementation) if 'self' keyword is provided before the variable named 'counter'.
# Instead of 'self' keyword we shall use class name, to make this work 'ExampleOne.counter += 1'.
class ExampleOne:
    counter = 0

    def __init__(self, name, surname):
        self.name = name
        self.surname = surname
        self.counter += 1


# It works, meaning list is being updated. Even if 'self' keyword is provided before variable named 'list'.
class ExampleTwo:
    list = []

    def __init__(self, name, surname):
        self.name = name
        self.surname = surname
        self.list.append([self.name, self.surname])

【问题讨论】:

    标签: python-3.x class variables


    【解决方案1】:

    self.counter,当查找一个值时,会检查实例后面的类;但是当分配一个值时,只会分配给实例(因为它首先尝试实例并且会成功 - 没有什么可以阻止它工作)。

    self.counter += 1 等价于self.counter = self.counter + 1;新计算的值,基于类属性,被分配为实例属性。

    self.list.append(...) 调用查找列表对象的方法;该对象的身份永远不会改变,并且没有分配。所以每次访问self.list 都会找到类属性,因为永远不会先找到任何实例属性

    有关更多技术细节,您可以查看例如How python attribute lookup process works?.

    您可能想知道为什么允许查找首先通过实例查找类属性。原因是它有时对多态有用;根据实例的子类型,可以在不同的类中找到类属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 2023-04-03
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多