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)
或者甚至更好的是c
用a
属性初始化
class Class:
def __init__(self):
self.a = 1 # all instances will have their own a attribute
Run Code Online (Sandbox Code Playgroud)