Ben*_*ey4 2 python pygame function
考虑 pygame 循环中的这一行:
pygame.display.set_mode().fill((0, 200, 255))
Run Code Online (Sandbox Code Playgroud)
来自:http : //openbookproject.net/thinkcs/python/english3e/pygame.html
一、你怎么知道set_mode中嵌套了一个填充函数?我在 pygame 文档中搜索过,在 set_mode 部分中没有关于填充的信息。
二、set_mode()
是pygame包的显示模块的一个函数。如何调用嵌套在另一个函数中的函数?我怎么能用print"hi"
这个函数调用(尝试过但得到一个 AttributeError):
def f():
def g():
print "hi"
Run Code Online (Sandbox Code Playgroud)
pygame.display.set_mode() 返回一个 Surface 对象。
从文档:
pygame.display.set_mode 初始化一个用于显示的窗口或屏幕 pygame.display.set_mode(resolution=(0,0), flags=0, depth=0): return Surface
所以你是.fill()
在表面对象上调用方法,而不是在函数上set_mode()
。
您可以在pygame的表面文档中找到表面对象上可用的方法。
您不能以这种方式调用嵌套函数。要在打印示例中获得所需的结果,您可以通过以下方式使用类:
class F():
def g(self):
print "hi"
Run Code Online (Sandbox Code Playgroud)
导致:
>>> F().g()
hi
Run Code Online (Sandbox Code Playgroud)
这是一个简单的例子来展示它是如何display.set_mode().fill()
工作的:
class Surface():
def fill(self):
print "filling"
class Display():
def set_mode(self):
return Surface()
Display().set_mode().fill()
Run Code Online (Sandbox Code Playgroud)
编辑:
您可以使用嵌套函数,但它的工作方式与使用对象和模块的方式略有不同:
def f():
def g():
print "hi"
return g
Run Code Online (Sandbox Code Playgroud)
导致:
>>> outerf = f()
>>> outerf()
hi
Run Code Online (Sandbox Code Playgroud)