[英]How to put a define inside a define function
我試圖弄清楚如何將一個define函數放在一個類里面的define函數中。 我想做的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()? 一些優雅的想法,因為它不是在其他方面,如在簡單方面。
這是一種不好的編碼方式......
沒有辦法在Guy class
下調用left
函數,因為它在move
函數的范圍內,並且與class
不同,在另一個函數中添加一個函數並不會使它成為它的屬性。
在inside函數是外部函數的屬性之前,無法使用封閉函數的名稱來調用它
如果
def move():
def left():
即如果函數內只有一個函數,則從move
函數返回left()
是可行的。
但是在這種情況下, move
功能范圍內有多個功能。
您應該尋找類似nested class
東西,並將其作為class
而不是函數進行move
我會避免嵌套方法和函數。
您的move
方法將在每次調用時重新編譯這些方向方法,並且只能從move
調用這些方向方法。
也許你想要一個帶有方向參數和自我的通用move
方法?
def move(self, direction):
if direction == "left":
pass //do something
//etc
class Guy():
def move(self,dir):
def left():
print "left!"
{'left':left}[dir]()
Guy().move("left")
雖然我沒有看到很多用例,但它會工作...
有一種方法可以實現類似於原始代碼的要求: Guy.move()
將調用move()函數,而Guy.move.right(Guy())
將調用move.right
函數。 唯一的區別是我必須明確地將self
對象傳遞給move.right。
我不鼓勵任何人采取這種方式,更像是'什么是python可以做'的事情。
def to_attr(f):
import inspect
import new
for c in f.func_code.co_consts:
if inspect.iscode(c):
g = new.function(c, globals())
setattr(f, g.func_name, g)
return f
class Guy(object):
@to_attr
def move(self):
def left(self):
pass
def right(self):
print "Right"
def up(self):
pass
def down(self):
pass
print "Move"
Guy.move.right(Guy())
Guy().move()
inspect
代碼是從Python中使用Introspecting給定函數的嵌套(本地)函數借來的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.