Search code examples
pythoninstance-variablesclass-method

How would an instance variable be used in a class method?


Is there a way that in a class methods I can use an instance variable to perform a calculation?

Very simplified, this is what I am attempting to do:

class Test:

  def __init__(self, a):
    self.a = a

  @classmethod
  def calculate(cls, b):
     return self.a + b

Solution

  • 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'