【问题标题】:fill() in pygame.display.set_mode().fill((0, 200, 255))pygame.display.set_mode().fill((0, 200, 255)) 中的 fill()
【发布时间】:2012-04-21 22:05:24
【问题描述】:

在 pygame 循环中考虑这一行:

pygame.display.set_mode().fill((0, 200, 255))

发件人: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"

【问题讨论】:

    标签: python function pygame


    【解决方案1】:

    pygame.display.set_mode() 返回一个 Surface 对象。

    来自documentation

    pygame.display.set_mode 初始化一个窗口或屏幕进行显示 pygame.display.set_mode(resolution=(0,0), flags=0, depth=0): return Surface

    所以你是在表面对象上调用方法.fill(),而不是在函数set_mode()上。

    您可以在 pygame 的surface documentation 中找到表面对象可用的方法。

    您不能以这种方式调用嵌套函数。 要在打印示例中获得所需的结果,您可以通过以下方式使用类:

    class F():
      def g(self):
        print "hi"
    

    导致:

    >>> F().g()
    hi
    

    这是一个简化的示例,用于展示 display.set_mode().fill() 的工作原理:

    class Surface():
        def fill(self):
            print "filling"
    
    class Display():
        def set_mode(self):
            return Surface()
    
    
    Display().set_mode().fill()
    

    编辑:

    您可以使用嵌套函数,但它的工作方式与使用对象和模块的方式略有不同:

    def f():
      def g():
        print "hi"
      return g
    

    导致:

    >>> outerf = f()
    >>> outerf()
    hi 
    

    【讨论】:

    • 对于 I. :您的示例不同主要是因为 Display 是一个类,而在 pygame 中它是一个模块。我想我明白了。谢谢!!现在我也明白了为什么 display.set_mode() 首先存储到变量中。所以对于 II.:你是说你根本不能调用嵌套在另一个函数中的函数。
    • 您可以调用嵌套在另一个函数中的函数。不过,它的做法略有不同。见:stackoverflow.com/questions/1589058/nested-function-in-python 编辑:你说得对,显示是一个模块。
    • 谢谢。但是我找不到如何调用嵌套函数。在您的链接中,有人指出您可以这样做(应用于我的示例):outerf = f() 然后 outerf() 但这不起作用。
    • 顺便说一句:我忘了在我原来的帖子的嵌套函数中添加 def 关键字。我改了。
    • @Bentley4 我用嵌套函数的示例更新了答案。
    猜你喜欢
    • 2017-07-22
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2018-01-07
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多