gpt4 book ai didi

python - 更改类中使用的变量?

转载 作者:行者123 更新时间:2023-12-01 08:16:14 27 4
gpt4 key购买 nike

我使用变量作为类中字符串的一部分,但是打印字符串显示变量在程序开始时设置的内容,而不是更改后的内容

我当前的代码基本上是这样说的:

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 值的最简单方法是创建类方法 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()

关于python - 更改类中使用的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54967445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com