如果要创建类变量,则必须在任何类方法之外(但仍在类定义之内)声明它:
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'