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.
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.
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.
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.
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.
Use self.__class__.classAttr
. This should work for both old & new style classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With