简体   繁体   中英

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

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'

如果要命名空间,请使用@staticmethod代替,并让用户传递变量,例如Test.calculate(a, b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM