2

Consider this line in the pygame loop:

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

From: http://openbookproject.net/thinkcs/python/english3e/pygame.html

I. How are you supposed to know there even is a fill function nested in set_mode? I searched in the pygame documentation and there is no information on fill in the set_mode section.

II. set_mode() is a function of the display module of the pygame package. How can I call a function nested in another function? How could I call print"hi" with this function(tried it but get an AttributeError):

def f():
    def g():
        print "hi"
Bentley4
  • 10,678
  • 25
  • 83
  • 134

1 Answers1

5

The pygame.display.set_mode() returns a Surface object.

From the documentation:

pygame.display.set_mode initialize a window or screen for display pygame.display.set_mode(resolution=(0,0), flags=0, depth=0): return Surface

So you are calling the method .fill() on the surface object, not on the function set_mode().

You can find the methods available on surface objects in the surface documentation of pygame.

You cannot call a nested function in that way. To get your desired result in your print example, you can use classes in the following way:

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

Resulting in:

>>> F().g()
hi

This is a simplified example to show how the display.set_mode().fill() works:

class Surface():
    def fill(self):
        print "filling"

class Display():
    def set_mode(self):
        return Surface()


Display().set_mode().fill()

Edit:

You can use nested functions, but it works slightly different from how you would do it with objects and modules:

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

Resulting in:

>>> outerf = f()
>>> outerf()
hi 
veiset
  • 1,973
  • 16
  • 16
  • For I. : Your example is different mainly because there `Display` is a class while in pygame it is a module. I think I get it. Thank you!! Now I also understand why display.set_mode() is stored into a variable first. So for II.: You are saying you simply cannot call a function nested in another function. – Bentley4 Apr 09 '12 at 15:18
  • You can call a function nested in another function. It is done slightly different though. See: http://stackoverflow.com/questions/1589058/nested-function-in-python Edit: You're right about display being a module. – veiset Apr 09 '12 at 15:24
  • Thnx. But I can't find how to call the nested fucntion though. In your link somebody points out you can do this(applied to my example): `outerf = f()` then `outerf()` But this doesn't work. – Bentley4 Apr 09 '12 at 20:39
  • Btw: I forgot to add the `def` keyword in the nested function in my original post. I changed it. – Bentley4 Apr 09 '12 at 20:53
  • 1
    @Bentley4 I updated the answer with an example of a nested function. – veiset Apr 09 '12 at 21:22