Python function not accessing a class variable

I am trying to access a class variable in an external function, however I get the AttributeError attribute, "the class has no attribute". My codes look 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' 

Other questions were asked similar to this, however all answers were said to use self and determine during init , which I did. Why I canโ€™t access this variable.

+4
source share
2 answers

If you want to create a class variable, you must declare it outside of 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' 

The reason your example does not work is because you are assigning a value to the instance variable.

The difference between the two is that when you create the class object, the class variable is created. While the instance variable will be created after creating the instance of the object and only after they have been assigned.

 class Example(object): def doSomething(self): self.othervariable = 'instance variable' >> foo = Example() 

Here we created an instance of Example , however, if we try to access othervariable , we get an error message:

 >> foo.othervariable AttributeError: 'Example' object has no attribute 'othervariable' 

Since othervariable is assigned inside doSomething - and we did not call ityet - it does not exist.

 >> foo.doSomething() >> foo.othervariable 'instance variable' 

__init__ is a special method that is automatically called whenever a class instance occurs.

 class Example(object): def __init__(self): self.othervariable = 'instance variable' >> foo = Example() >> foo.othervariable 'instance variable' 
+12
source

You are a little confused about what is an attribute of a class and what is not.

  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() 

Class variables are always accessible from the class:

 print(aclass.somevar1) # prints 'a value' 

Similarly, all instances have access to all instance variables:

 print(inst.somevar2) # prints 'another value' 
+10
source

Source: https://habr.com/ru/post/1482051/


All Articles