我想从不同文件中定义的函数访问对象(特别是其变量)。让我们看一个例子:
档案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]
...
但它使用额外的资源,使代码更长,在更复杂的情况下更麻烦。
有没有办法直接在对象的变量上完成工作,但是将函数保存在单独的文件中?
EDIT 已经有了这个问题的答案,但也许我会在其中一个答案中加入澄清(引用对此答案的评论):
我希望能够添加其他"敌人"没有在这个地方制作冗长的代码(所以
forward()
是一种包装器,决定在不同的情况下做什么)。如果此函数位于不同的文件中,它也更具可读性。想想会有100个敌人的情况"每个都需要更改100个变量,这些变量是每个包含1M个条目的列表。有没有比把敌人更好的方式"进入其他文件并直接在文件中更改变量?
答案 0 :(得分:2)
您需要将对象作为参数移交。
在功能中:
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!
答案 1 :(得分:0)
可以做到这一点,虽然我不知道为什么你真的想这样做。
在forward
和__init__
方法中,您会注意到您正在传递self
,这是您正在操作的Encounter
的实例。这就是为什么当你致电self.number = 42
时,你可以knight.number
并获得正确的号码。
由于self
只是一个对象,您可以将其传递给' enemies.py'中的函数。
尝试:
# grail.py
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
#enemies.py
def knightofni(that):
that.number = 1
that.who = "We've encountered Knight of Ni."
def frenchman(that):
that.number = 4
that.who = "We've encountered French."