需要不同参数时,如何在类内使用if / elif?

时间:2019-03-24 06:13:42

标签: python pygame

我正在做一个类,以放入所有有关pygame键盘的命令,至少是我需要的所有命令,但是当我使用if or else等于我要稍后定义的“变量”时,它将返回错误告诉我它没有定义。

我对技术领域的知识还不够了解,对不起。我开始使用button作为key()的参数,并且遇到相同的错误,然后尝试使用__init__(),但是我可以使用它(不确定如何使用),然后以这种方式进行制作...

class control():
    def button(self, button):
        self.button = button
    def exit(self):
        if event.type == pygame.QUIT:
            pygame.quit()
    def key(self, axis, speed):
        if event.type == pygame.KEYDOWN:
            if event.key == self.button:
                axis = 0
                axis = speed


ctrl = control()
w = control().button(K_w)
s = control(K_s)
UP = control(K_UP)
DOWN = control(K_DOWN)


while True:
    for event in pygame.event.get():
        ctrl.exit()  
        w.key(y1, -5)
        s.key(y1, +5)
        UP.key(y2, -5)
        DOWN.key(y2, +5)
 File "C:/Users/Smith/PycharmProjects/untitled/venv/test0002.py", line 25, in <module>
    w = control().button(K_w)
NameError: name 'K_w' is not defined

我想使用键功能定义按钮,因此我可以稍后在每次键盘输入时使用它,而不必每次都重新写一次。

1 个答案:

答案 0 :(得分:0)

错误消息

  

未定义名称“ K_w”

发生,因为您忘记了模块名称空间。

该常量的名称为 static Int64 substrings(string n) { string p = string.Empty, q = string.Empty, r = string.Empty; char[] c = n.ToCharArray(); string s = string.Empty; Int64 res = 0; for (int x = 0; x < n.Length; x++) { res += Convert.ToInt64(n[x].ToString()); } for (int x = 0; x < n.Length; x++) { if (x > 0) { p = n[x - 1].ToString(); q = n[x].ToString(); r = p + "" + q; p = q; q = r[0].ToString(); res += Convert.ToInt64(r); } } for(int x = 0; x < n.Length; x++) { if (n.Length > 2) { s += n[x]; } } if (n.Length > 2) { return res + Convert.ToInt64(s); } else { return res; } } ,而不是pygame.K_w。常量放置在pygame模块的命名空间中。

使用常量的完整名称:

K_w

或导入pygame常量,请参见pygame.locals

w = control().button(pygame.K_w)

另外,变量from pygame.locals import * # [...] w = control().button(K_w) 从未定义,因为w确实会生成对象,但是control()不会返回任何值。方法按钮应返回button()

self

但是我建议在类class control(): def button(self, button): self.button = button return self 中实现构造函数,而不要在方法control中实现(当然,您可以同时使用两者):

button

方法class control(): def __init__(self, button=0): self.button = button ctrl = control() w = control(K_w) s = control(K_s) UP = control(K_UP) DOWN = control(K_DOWN) 必须返回参数key的新值:

axis
相关问题