gpt4 book ai didi

python - 从不同文件更改对象的变量

转载 作者:行者123 更新时间:2023-12-01 04:11:21 25 4
gpt4 key购买 nike

我想从不同文件中定义的函数访问对象(特别是它的变量)。让我们看一个例子:

文件 1 - grail.py

import enemies

class Encounter:
def __init__(self):
self.counter = 1
self.number = 0
self.who = "We've encountered no one."

def forward(self):
if self.counter == 1:
enemies.knightofni()
elif self.counter == 2:
enemies.frenchman()
else:
self.number = 42
self.who = "We've found the Grail!"
self.counter += 1

knight = Encounter()
for i in range(4):
print(str(knight.number) + " " + knight.who)
knight.forward()

文件 2 - enemies.py(我可能需要此文件中的某些内容)

def knightofni():
Object.number = 1
Object.who = "We've encountered Knight of Ni."

def frenchman():
Object.number = 4
Object.who = "We've encountered French."

输出应显示:

0 We've encountered no one.
1 We've encountered Knight of Ni.
4 We've encountered French.
42 We've found the Grail!

我知道您可以通过从文件 enemies.py 中的函数返回某些内容来实现输出,例如函数 frenchman() 可能如下所示:

def frenchman():
return [4, "We've encountered French."]

grail.py 中,我应该更改代码以收集 frenchman() 返回的内容:

...
elif self.counter == 2:
spam = enemies.frenchman()
self.number = spam[0]
self.who = spam[1]
...

但它使用额外的资源,使代码更长,并且在更复杂的情况下更麻烦。

有没有办法直接在对象的变量上完成工作,但将函数保存在单独的文件中?

编辑这个问题已经有了答案,但也许我会在其中一个答案中看到疑问而添加澄清(引用对此答案的评论):

I want it to be possible to add other "enemies" without making lengthy code in this place (so forward() is kind of a wrapper, place where it is decided what to do in different situations). It is also more readable if this functions are in different file.

Think of situation where there would be 100 "enemies" and each would need to change 100 variables which are lists with 1M entries each. Is there a better way than putting "enemies" into other file and changing variables directly in the file?

最佳答案

问题

您需要将对象作为参数移交。

在函数中:

def knightofni(obj):
obj.number = 1
obj.who = "We've encountered Knight of Ni."

在类里面使用它时:

enemies.knightofni(self)

frenchman() 执行相同的操作。

完整代码

grail.py

import enemies

class Encounter:
def __init__(self):
self.counter = 1
self.number = 0
self.who = "We've encountered no one."

def forward(self):
if self.counter == 1:
enemies.knightofni(self)
elif self.counter == 2:
enemies.frenchman(self)
else:
self.number = 42
self.who = "We've found the Grail!"
self.counter += 1

knight = Encounter()
for i in range(4):
print(str(knight.number) + " " + knight.who)
knight.forward()

enemies.py:

def knightofni(obj):
obj.number = 1
obj.who = "We've encountered Knight of Ni."

def frenchman(obj):
obj.number = 4
obj.who = "We've encountered French."

输出:

0 We've encountered no one.
1 We've encountered Knight of Ni.
4 We've encountered French.
42 We've found the Grail!

关于python - 从不同文件更改对象的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34910228/

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