我试图访问外部函数中的类变量,但是我得到了AttributeError,"类没有属性"我的代码看起来像这样:
class example():
def __init__():
self.somevariable = raw_input("Input something: ")
def notaclass():
print example.somevariable
AttributeError: class example has no attribute 'somevariable'
Run Code Online (Sandbox Code Playgroud)
其他问题与此类似,但所有答案都表示在init期间使用self和define ,我做了.为什么我无法访问此变量.
Car*_*s V 15
如果要创建类变量,则必须在任何类方法之外声明它(但仍在类定义中):
class Example(object):
somevariable = 'class variable'
Run Code Online (Sandbox Code Playgroud)
有了这个,您现在可以访问您的类变量.
>> Example.somevariable
'class variable'
Run Code Online (Sandbox Code Playgroud)
您的示例无效的原因是您要为instance变量赋值.
两者之间的区别在于class,一旦创建了类对象,就会创建一个变量.而instance一旦对象被实例化并且仅在它们被分配之后将创建变量.
class Example(object):
def doSomething(self):
self.othervariable = 'instance variable'
>> foo = Example()
Run Code Online (Sandbox Code Playgroud)
在这里我们创建了一个实例Example,但是如果我们尝试访问,othervariable我们将收到一个错误:
>> foo.othervariable
AttributeError: 'Example' object has no attribute 'othervariable'
Run Code Online (Sandbox Code Playgroud)
由于othervariable在内部分配doSomething- 我们还没有调用ityet - 它不存在.
>> foo.doSomething()
>> foo.othervariable
'instance variable'
Run Code Online (Sandbox Code Playgroud)
__init__ 是一种特殊的方法,只要发生类实例化就会自动调用它.
class Example(object):
def __init__(self):
self.othervariable = 'instance variable'
>> foo = Example()
>> foo.othervariable
'instance variable'
Run Code Online (Sandbox Code Playgroud)
g.d*_*d.c 11
你对什么是类属性有点困惑,什么不是.
class aclass(object):
# This is a class attribute.
somevar1 = 'a value'
def __init__(self):
# this is an instance variable.
self.somevar2 = 'another value'
@classmethod
def usefulfunc(cls, *args):
# This is a class method.
print(cls.somevar1) # would print 'a value'
def instancefunc(self, *args):
# this is an instance method.
print(self.somevar2) # would print 'another value'
aclass.usefulfunc()
inst = aclass()
inst.instancefunc()
Run Code Online (Sandbox Code Playgroud)
始终可以从类中访问类变量:
print(aclass.somevar1) # prints 'a value'
Run Code Online (Sandbox Code Playgroud)
同样,所有实例都可以访问所有实例变量:
print(inst.somevar2) # prints 'another value'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22456 次 |
| 最近记录: |