【问题标题】:What is the correct way to access class variable inside class method? self.class_variable or class_name.class_variable?在类方法中访问类变量的正确方法是什么? self.class_variable 还是 class_name.class_variable?
【发布时间】:2021-11-04 11:07:41
【问题描述】:
class Employee:
    location = "south"

    def describe(self):
        print(self.location)
   

我应该使用 self.class_variable 在类方法中访问类变量吗?

class Employee:
    location = "south"

    def describe(self):
        print(Employee.location)

或者我应该使用class_name.class_variable? 哪一个是正确的约定? 这两者有区别吗?

编辑 1: 因此,除了人们给出的其他答案之外,我发现 如果您更改 self.class_variable,它将仅针对该实例更改它 如果您更改 class_name.class_variable,它将为所有当前和未来的实例更改它。 希望对您有所帮助。

【问题讨论】:

    标签: python class oop methods class-variables


    【解决方案1】:

    如果您子类化,差异就会变得相关:

    >>> class Employee:
    ...     location = "south"
    ...     def describe_self(self):
    ...         print(self.location)
    ...     def describe_class(self):
    ...         print(Employee.location)
    ...
    >>> class Salesman(Employee):
    ...     location = "north"
    ...
    >>> Employee().describe_self()
    south
    >>> Employee().describe_class()
    south
    >>> Salesman().describe_self()
    north
    >>> Salesman().describe_class()
    south
    

    因为如果子类化,self 的类型实际上可能不是Employee

    【讨论】:

      【解决方案2】:

      是的,两者之间是有区别的。

      class Employee:
          location = "south"
      
      
      class EmployeeSelf(Employee):
          def __str__(self):
              return self.location
      
      
      class EmployeeEmployee(Employee):
          def __str__(self):
              return Employee.location
      
      
      emp = EmployeeSelf()
      emp.location = 'north'
      print(emp)
      
      emp0 = EmployeeEmployee()
      emp0.location = 'north'
      print(emp0)
      

      看看这个例子。虽然标识符 self 指向对象本身,但 Employee 标识符指向类。

      【讨论】:

      • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 2020-05-06
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多