【问题标题】:Python how to share variable between class methods, and what is the difference between instance attributes and class attributesPython如何在类方法之间共享变量,实例属性和类属性有什么区别
【发布时间】:2020-12-21 10:58:41
【问题描述】:

例如:

class MyClass:

    def __init__(self,Attr1):
        self.Attr1 = Attr1

    def method1(self):
        self.var1 = [some codes involves Attr1]

    def method2(self):
        self.var2 = [some codes involves var1 from method1]

可行吗?但是函数中的变量是函数的局部变量。我不知道我是否可以从method1 拨打var1

我能想到的另一种方法是在__init__ 中设置self.var1,所以它是一个类属性,因此我可以在method2 中调用它。但是我不想有一个很大的__init__

我还阅读了一些关于类属性和实例属性的内容——这两者有什么区别?

【问题讨论】:

  • 按照您目前的编写方式,self.var1 是类的本地文件,而不是method1 的本地文件。它也可以从 method2 调用。但是,您需要先调用 method1 才能对其进行初始化。最好直接在init下做这个
  • “可行吗?” - 你有没有尝试过?请提供完整的工作代码(即用真实(可能是玩具或示例)代码替换“一些代码”
  • self 指的是实例。如果对象被实例化,您绝对可以使用您在 method1 其他地方设置的实例属性。

标签: python oop self class-attributes


【解决方案1】:

实例属性

类中以self.开头的变量属于特定的奇异类实例(不属于特定的方法),所以非常实用。

你可以在类构造函数中初始化它们:

class A:
    def __init__(self):
        self.instance_attribute = 'instance attribute'

您可以分别更改每个实例的值:

a1 = A()
a2 = A()

a2.instance_attribute = 'sabich'

# 'instance attribute' (unchanged)
print(a1.instance_attribute)

# 'sabich'
print(a2.instance_attribute)

类属性

class A:
    a = "class attribute"

类属性对所有类实例都是通用的,并且归类所有。

它们可以通过类名访问:

# 'class attribute'
print(A.a)

或通过具体实例:

a1 = A()

# 'class attribute'
print(a1.a)

【讨论】:

    【解决方案2】:

    您已经在使用self.,因此您的 var1 的范围是类而不是方法。

    因此,如果您将 var1 称为 self.var1 并且首先调用 method1,则可以在任何其他类方法中使用 var1。

    【讨论】:

      【解决方案3】:

      可行吗?

      是的。

      But the variables in functions are local to the function.
      

      不,它们是实例属性,也就是说,它们是类的某些实例的属性。

      不知道能不能从method1拨打var1

      可以,但您需要创建一个实例,然后调用该实例的方法。

      我能想到的另一种方法是设置self.var1 __init__ 所以它是一个类属性,所以我可以调用它 method2

      最好在构造函数中设置它,因为这样您就不必担心method1 是否被调用。但是你可以在method2 中使用它而没有问题。

      但是我不想有一个很大的__init__

      您可以创建辅助方法并调用它们。

      I also read something about a class attributes and an instance attributes — what's the difference between the two?
      

      类属性是类的属性,即它们是整个实例集的属性。实例属性是属性的实例。想想 stackoverflow.com 的用户。每个用户都有一个用户名,这是实例级别的。但是,用户数量是用户作为一个整体的一个属性。

      【讨论】:

        猜你喜欢
        • 2021-12-26
        • 1970-01-01
        • 2015-09-10
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多