How to Access "Static" Class Variables Within Methods in Python

How can I access static class variables within methods in Python?

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

How can static method access class variable in Python?

You can access it as InviteManager.INVITE_MESSAGE, but a cleaner solution is to change the static method to a class method:

@classmethod
@missing_input_not_allowed
def invite(cls, email):
return cls.INVITE_MESSAGE

(Or, if your code is really as simple as it looks, you can replace the whole class with a bunch of functions and constants in a module. Modules are namespaces.)

Static class variables and methods in Python

Variables declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass:
... i = 3
...
>>> MyClass.i
3

As @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.

See what the Python tutorial has to say on the subject of classes and class objects.

@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class C:
@staticmethod
def f(arg1, arg2, ...): ...

@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument.

How to access class variable inside methods of that class in python?

There are two ways to access it

first: self.__class__.PAD_token

second: self.PAD_token

If you just need to access class variables, the first one is recommended

How do I use a static variable inside a class in Python

There are two ways to access a class attribute: you can either access it directly on a class, or you can read it through self (but not rebind it). Accessing a class attribute through self won't work if there is already a value set directly on the instance so you would normally try to use the class to access a class attribute.

class Cls:
counter = 0
def __init__(self, name):
self.name = name
Cls.counter += 1
def count(self):
return Cls.counter

When you write self.counter += 1 this is a shorthand for self.counter = self.counter + 1 and as with any other binding through self it sets an instance attribute.

This can be useful if you want a default value for instance attributes, you can set them as class attributes and then just update them in the instances which want different values, but to avoid confusion you probably want to avoid using self at all when accessing class attributes.

You can also consider making the count method into a class method and moving the increment into another method:

@classmethod
def increment(cls):
cls.counter += 1

@classmethod
def count(cls):
return cls.counter

if you do that then each subclass will have its own independent counter. That may or may not be what you want here. The cls parameter here is the class that was actually instantiated, this can be useful if you can a whole class hierarchy, or even just a base class CountsInstances where you can put this code once and reuse it with multiple independent counters.

Decorating each function with @staticmethod will give you something close to the Java code:

class Cls:
counter = 0
def __init__(self, name):
self.name = name
self.increment()

@staticmethod
def increment():
Cls.counter += 1

@staticmethod
def count():
return Cls.counter

How to call static method from a static variable inside a class?

It looks like you'd like to initialize the value of a static class variable using a static function from that same class as it's being defined. You can do this using the following syntax taken from this answer but with an added parameter:

class X:
@staticmethod
def do_something(par):
return par

static_var = do_something.__func__(5)

print(X.static_var)

Output:

5

Try it!

Referencing a static method of the class X directly inside the X definition fails because X doesn't yet exist. However, since you have defined the @staticmethod do_something, you can call its __func__ attribute with the parameter and assign the result to static_var.

Having said that, more information about the underlying design goal you're trying to implement could reveal a better approach.

Use class name to access static variables

Don't forget to read the comments.


For anybody looking for an answer to this, disregarding for the moment whether mixing static and instance variables is a good idea.

There are two simple ways to approach this.

First way

class MyClass():
static_variable = 'VARIABLE'

def __init__(self):
self.instanceVariable = 'test'

def access_static(self):
print(__class__.static_variable)

Second way

class MyClass():
static_variable = 'VARIABLE'

def __init__(self):
self.instanceVariable = 'test'

def access_static(self):
print(self.static_variable)

An instance variable can be accessed using class.static_variable, or using
self.static_variable as long as an instance variable hasn't been defined for self.static_variable somewhere in the code.

Using self would make it ambiguous as to whether you are accessing a static variable or instance variable though, so my preferred way of doing it would be to simply prepend static_variable with class instead of ClassName.static_variable

Python: Accessing static class variables from inside the class

Since none of the methods are called until after Sequence is fully defined, you can refer to Sequence.__map__ without any trouble. For example:

def __setattr(self, name, value):
print('Setting atr', name, 'with val', value)
try:
self[Sequence.__map__[name]] = value
except KeyError:
object.__setattr__(self, name, value)

As an aside, here's a demonstration that class attributes may be accessed via objects as long as an instance attribute with the same name does not also exist:

class Foo:
i = 3
def __init__(self, overwrite):
if overwrite:
self.i = 4

f = Foo(False)
id(f.i) == id(Foo.i) # Should be True
f = Foo(True)
id(f.i) == id(Foo.i) # Should be False

python class variable in static method

If the attributes are going to be static, don't initialize them in the initializer method, declare them outside at the class level, not at method level.

But why are you initializing class attributes in the initializer? every instance that you create will overwrite their values!

I believe you're confusing what instance attributes and class attributes are used for. Why don't you try using only instance attributes? all things considered, having static data is not a good idea. For example:

class MyConnection:
def __init__(self, hostname, port, user, password):
self.myhostname = hostname
self.myport = port
self.myuser = user
self.mypassword = password
@staticmethod
def connect():
my_session = MyConnection()
print my_session.myuser # just an example


Related Topics



Leave a reply



Submit