Python函数不访问类变量 [英] Python function not accessing class variable
问题描述
我正在尝试访问外部函数中的类变量,但是出现 AttributeError,类没有属性"我的代码如下所示:
I am trying to access a class variable in an outside function, however I get the AttributeError, "Class has no attribute" My codes looks something like this:
class example():
def __init__():
self.somevariable = raw_input("Input something: ")
def notaclass():
print example.somevariable
AttributeError: class example has no attribute 'somevariable'
其他问题与此类似,但所有答案都说在 init 期间使用 self 和define,我就是这样做的.为什么我不能访问这个变量.
Other questions have been asked similar to this however all the answers said to use self and define during init, which I did. Why can't I access this variable.
推荐答案
如果你想创建一个类变量,你必须在任何类方法之外(但仍然在类定义内)声明它:
If you want to create a class variable, you must to declare it outside any class methods (but still inside the class definition):
class Example(object):
somevariable = 'class variable'
有了这个,您现在可以访问您的类变量.
With this you can now access your class variable.
>> Example.somevariable
'class variable'
<小时>
您的示例不起作用的原因是您正在为 instance
变量赋值.
两者的区别在于,class
变量在创建类对象后立即创建.而 instance
变量将在对象被实例化后创建,并且只有在它们被分配之后才会被创建.
The difference between the two is that a class
variable is created as soon as the class object is created. Whereas an instance
variable will be created once the object has been instantiated and only after they have been assigned to.
class Example(object):
def doSomething(self):
self.othervariable = 'instance variable'
>> foo = Example()
这里我们创建了一个Example
的实例,但是如果我们尝试访问othervariable
,我们会得到一个错误:
Here we created an instance of Example
, however if we try to access othervariable
we will get an error:
>> foo.othervariable
AttributeError: 'Example' object has no attribute 'othervariable'
由于在 doSomething
内部分配了 othervariable
- 我们还没有调用 ityet - 所以它不存在.
Since othervariable
is assigned inside doSomething
- and we haven't called ityet -, it does not exist.
>> foo.doSomething()
>> foo.othervariable
'instance variable'
<小时>
__init__
是一个特殊的方法,它会在类实例化发生时自动调用.
__init__
is a special method that automatically gets invoked whenever class instantiation happens.
class Example(object):
def __init__(self):
self.othervariable = 'instance variable'
>> foo = Example()
>> foo.othervariable
'instance variable'
这篇关于Python函数不访问类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!