Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access class variable from instance

Tags:

python

I have this class:

class ReallyLongClassName:      static_var = 5      def instance_method(self):         ReallyLongClassName.static_var += 1 

Is there some way to access the static variable using the self variable? I'd rather do something like class(self).static_var += 1, because long names are unreadable.

like image 629
Jacklynn Avatar asked Aug 29 '14 23:08

Jacklynn


People also ask

Can an instance method access a class variable?

Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.

How do you access class variables?

To access class variables, you use the same dot notation as with instance variables. To retrieve or change the value of the class variable, you can use either the instance or the name of the class on the left side of the dot.

Can an instance method access class variable Python?

There are two ways to access the instance variable of class: Within the class in instance method by using the object reference ( self ) Using getattr() method.

How can you access class variables outside the class?

If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.


1 Answers

Use self.__class__.classAttr. This should work for both old & new style classes.

like image 121
Judah Meek Avatar answered Sep 27 '22 00:09

Judah Meek