Python function not accessing class variable -
i trying access class variable in outside function, attributeerror, "class has no attribute" codes looks this:
class example(): def __init__(): self.somevariable = raw_input("input something: ") def notaclass(): print example.somevariable attributeerror: class example has no attribute 'somevariable' other questions have been asked similar answers said use self , define during init, did. why can't access variable.
if want create class variable, must declare outside class methods (but still inside class definition):
class example(object): somevariable = 'class variable' with can access class variable.
>> example.somevariable 'class variable' the reason why example isn't working because assigning value instance variable.
the difference between 2 class variable created class object created. whereas instance variable created once object has been instantiated , after have been assigned to.
class example(object): def dosomething(self): self.othervariable = 'instance variable' >> foo = example() here created instance of example, if try access othervariable error:
>> foo.othervariable attributeerror: 'example' object has no attribute 'othervariable' since othervariable assigned inside dosomething - , haven't called ityet -, not exist.
>> foo.dosomething() >> foo.othervariable 'instance variable' __init__ special method automatically gets invoked whenever class instantiation happens.
class example(object): def __init__(self): self.othervariable = 'instance variable' >> foo = example() >> foo.othervariable 'instance variable'
Comments
Post a Comment