在一个方法中创建的属性在其他方法中不存在

use*_*239 10 python attributes class

这里我有一个属性'a',它在第一类方法中定义,应该在第二类中更改.按顺序调用它们时,会显示以下消息:

AttributeError:'Class'对象没有属性'a'

我找到的唯一方法 - 在第二种方法中再次定义'a',但在实际代码中它有很长的继承和应用程序将被混乱.为什么不起作用?不是self.a等于Class.a

class Class(object):
    def method_1(self):
        self.a = 1
    def method_2(self):
        self.a += 1

Class().method_1()
Class().method_2()
Run Code Online (Sandbox Code Playgroud)

Fel*_*ipe 15

简短的回答,没有.代码的问题在于每次创建新实例时.

编辑:正如下面提到的那样,Class.a和之间有很大的不同c.a.实例属性(第二种情况)属于每个特定对象,而类属性属于该类.请查看下面的abarnert评论或此处的讨论以获取更多信息.

你的代码相当于

c1 = Class()
c1.method_1()  # defines c1.a (an instance attribute)
c2 = Class()
c2.method_2()  # c2.a undefined (the c2 instance doesn't have the attribute)
Run Code Online (Sandbox Code Playgroud)

你可能想要做类似的事情

c = Class()
c.method_1()  # c.a = 1
c.method_2()  # c.a = 2
print "c.a is %d" % c.a  # prints "c.a is 2"
Run Code Online (Sandbox Code Playgroud)

或者甚至更好的是ca属性初始化

class Class:
    def __init__(self):
        self.a = 1  # all instances will have their own a attribute
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案......但是可能有必要解释一下,'self.a`不等于`Class.a`,而不仅仅是断然说"不".`self.a`是一个_instance属性_:每个`Class`实例都有自己的副本.`Class.a`是一个_class属性_:类本身有一个副本,无论有多少个实例(有点像C++和相关语言中的静态成员).如果你不知道为什么你想要一个类属性,你不需要一个. (9认同)