Python函数无法访问类变量
我正在尝试在外部函数中访问类变量,但是出现AttributeError,“类没有属性”,我的代码如下所示:
class example():
def __init__():
self.somevariable = raw_input("Input something: ")
def notaclass():
print example.somevariable
AttributeError: class example has no attribute 'somevariable'
有人问过与此类似的其他问题,但是所有答案都说要使用self并在 init 期间定义,这就是我所做的。为什么我不能访问此变量。
-
如果要创建类变量,则必须在任何类方法之外(但仍在类定义之内)声明它:
class Example(object): somevariable = 'class variable'
现在,您可以访问您的类变量。
>> Example.somevariable 'class variable'
您的示例无法正常运行的原因是因为您正在为
instance
变量分配值。两者之间的区别在于
class
,一旦创建了类对象,便会立即创建一个变量。而instance
一旦 实例化
对象并且仅在将它们分配给对象之后,将创建一个变量。class Example(object): def doSomething(self): self.othervariable = 'instance variable' >> foo = Example()
在这里,我们创建了的实例
Example
,但是如果尝试访问othervariable
,则会收到错误消息:>> foo.othervariable AttributeError: 'Example' object has no attribute 'othervariable'
由于
othervariable
在内部分配doSomething
-我们还没有称为ityet-,因此不存在。>> foo.doSomething() >> foo.othervariable 'instance variable'
__init__
是一种特殊的方法,只要发生类实例化,该方法就会自动被调用。class Example(object): def __init__(self): self.othervariable = 'instance variable' >> foo = Example() >> foo.othervariable 'instance variable'