How would an instance variable be used in a class method?
在类方法中,是否可以使用实例变量执行计算?
非常简单,这就是我要做的:
1 2 3 4 5 6 7 8 | 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.
如果要缓存类范围的值,以下是基本选项:
显式设置值:
1 2 3 4 5 6 7 8 9 10 11 12 | 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' |
在类初始化时设置值:
1 2 3 4 5 6 7 8 9 10 11 | class Foo: print('Setting foo') foo = 'bar' def print_foo(self): print(self.__class__.foo) # => 'Setting foo' Foo() Foo() Foo().print_foo() # => 'bar' |
在第一个实例init设置值:
1 2 3 4 5 6 7 8 9 10 11 12 | 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' |
如果要使用名称间距,请使用