import pygame
from pygame.locals import *
pygame.init()
class levelClass(object):
def __init__(self, name):
self.name = name
this init name of window
def makeWindow(self):
screen = pygame.display.set_mode((800,800))
pygame.display.set_caption(self.name)
def drawName(self):
myfont = pygame.font.SysFont("monospace", 25)
label = myfont.render(self.name, 1, (255,0,0))
screen.blit(label, (400,400))
level = levelClass('Level 0')
while True:
level.__init__()
level.drawName()
level.makeWindow()
for event in pygame.event:
if event.type == QUIT:
pygame.exit()
sys.close()
pygame.display.update()
this will create a window with name Level 0 and write this on window, but i see this error: init () missing 1 required positional argument: 'name'
You don't need to call __init__(...)
explicitly, when you create the object:
level = levelClass('Level 0')
it implicitly calls __init__(...)
with the argument "Level 0", so you don't need to do it in the while
loop.
The __init__
method is roughly what represents a constructor in Python, so it is supposed to be executed just one time, when you create the object.
Edit: In conclusion, you must not call __init__()
, when you create the object:
level = levelClass('Level 0')
it is called implicitly, so to correct your problem, delete this line:
level.__init__()
levelClass.__init__
is defined like this:
def __init__(self, name):
so it requires a name argument.
So either eliminate the call to
level.__init__()
(why do you need it anyway?) or change
level.__init__()
to
level.__init__(name)
for some value of name
. You would use this only if you wished to change level.name
with each iteration of the while-loop
. This might be useful if there was more stuff going on in the __init__
method than just setting
self.name = name
-- for example, if __init__
were loading a different map for each level. If all that __init__
is doing is setting the name, then you don't need to call __init__
to change the name
attribute; you could just set it directly:
level.name = somename
PS. When an instance (eg level
) calls the method __init__
like this:
level.__init__(somename)
Python calls
levelClass.__init__(level, somename)
Thus self
is set to the value level
, and name
is set to somename
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.