如何在 class 方法中使用实例变量?

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

有没有一种方法可以在 class 方法中使用实例变量来执行计算?

非常简单,这就是我想要做的:

class Test:

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

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

如果您想要命名空间,请改用 @staticmethod 并让用户传入变量,例如Test.calculate(a, b)

all I want is to declare a variable 'a', then use it in a class method for calculation purposes.

如果要缓存 class 范围的值,这些是您的基本选项:

明确设置值:

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'

在 class 初始设置值:

class Foo:
    print('Setting foo')
    foo = 'bar'

    def print_foo(self):
        print(self.__class__.foo)
# => 'Setting foo'

Foo()
Foo()
Foo().print_foo()  # => 'bar'

在第一个实例初始化时设置值:

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'