我在类中使用变量作为字符串的一部分,但是打印字符串会显示变量在程序开始时设置的内容,而不是更改为
我目前的代码基本上说:
b = 0
class addition:
a = 1 + b
def enter():
global b;
b = input("Enter a number: ")
print(addition.a) - Prints "1" regardless of what is typed in
enter()
如何“重新运行”类以使用赋值给函数中变量的值?
使用重新分配的b值的最简单方法是创建classmethod a
:
b = 0
class addition:
@classmethod
def a(cls):
return 1 + b
def enter():
global b;
b = int(input("Enter a number: ")) # convert string input to int
print(addition.a()) # calling a with ()
enter()
但它破坏了你原来的语义,在没有addition.a
的情况下调用()
。如果你真的需要保存它,有一种使用元类的方法:
class Meta(type):
def __getattr__(self, name):
if name == 'a':
return 1 + b
return object.__getattr__(self, name)
b = 0
class addition(metaclass=Meta):
pass
def enter():
global b;
b = int(input("Enter a number: "))
print(addition.a) # calling a without ()
enter()