all I want is to declare a variable 'a', then use it in a class method for calculation purposes.
If you want to cache a class-wide value, these are your basic options:
Set value explicitly:
class Foo:
@classmethod
def set_foo(cls):
print('Setting foo')
cls.foo = 'bar'
def print_foo(self):
print(self.__class__.foo)
Foo.set_foo() # => 'Setting foo'
Foo()
Foo().print_foo() # => 'bar'
Set value at class init:
class Foo:
print('Setting foo')
foo = 'bar'
def print_foo(self):
print(self.__class__.foo)
# => 'Setting foo'
Foo()
Foo()
Foo().print_foo() # => 'bar'
Set value at first instance init:
class Foo:
def __init__(self):
if not hasattr(self.__class__, 'foo'):
print('Setting foo')
self.__class__.foo = 'bar'
def print_foo(self):
print(self.__class__.foo)
Foo() # => 'Setting foo'
Foo()
Foo().print_foo() # => 'bar'
selfin a class method. Your method would work perfectly fine as a normal instance method. Why push square peg in a round hole? i.e. why do you think you should have a class method, if you are doing calculations on an instance? Your "very simplified" might have been too simplified to understand - all I see is wrong code easily fixable by removing@classmethodand replacingclswithself..aof which instance should be used in that method? You don't have a preferredselfinstance, but you could pass an instance (or multiple instances) as explicit parameter to the class function if you really need to.__get__method of a descriptor with both the instance and the class. See docs.python.org/3/howto/descriptor.html#functions-and-methods.