gpt4 book ai didi

python - 如何将定义放在定义函数中

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:15 26 4
gpt4 key购买 nike

我正在尝试弄清楚如何将定义函数放入类内的定义函数中。我想做的 Python 代码:

class Guy():
def move(self):
def left(self):
//compute
def right(self):
//compute
def up(self):
//compute
def down(self):
//compute

然后可以稍后在程序中调用 Guy.move.right()。解释器给我一个错误,说“函数没有正确的属性”或类似的东西。有什么方法可以做到这一点,而不必将我的函数从移动函数中取出并调用它们 Guy.right、Guy.left 等?

最佳答案

函数通常没有向外部范围公开的字段和其他函数。这通常是对象的工作。但是你可以用类似...的东西来做到这一点

class Guy():
class Move():
def __init__(self):
self.whatevs = "whatevs"
def left(self):
print("left")
pass
#compute
def right(self):
print("right")
pass
#compute
def up(self):
print("up")
pass
#compute
def down(self):
print("down")
pass
#compute

def __init__(self):
self.move = self.Move()

guy = Guy()
guy.move.left()

不过我很确定这不是好的设计。你想做 guy.move.left() 有什么原因吗?一些优雅的想法,因为它不是以其他方式出现的,比如简单。

关于python - 如何将定义放在定义函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13716669/

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