How to use an if/elif inside a class when you need different parameters?What is the difference between old style and new style classes in Python?How do you test that a Python function throws an exception?How do you split a list into evenly sized chunks?How do you change the size of figures drawn with matplotlib?Difference between abstract class and interface in PythonHow do you remove duplicates from a list whilst preserving order?How can you profile a Python script?How do you read from stdin?How to make a class JSON serializableHow do you append to a file in Python?

In general, would I need to season a meat when making a sauce?

Ticket sales for Queen at the Live Aid

How many chess players are over 2500 Elo?

Minimum number of comparisons in comparison-based sorting algorithms

Approximate solution : factorial and exponentials

What is the most important source of natural gas? coal, oil or other?

Canon 70D often overexposing or underexposing shots

Would Brexit have gone ahead by now if Gina Miller had not forced the Government to involve Parliament?

Does this degree 12 genus 1 curve have only one point over infinitely many finite fields?

Why are C64 games inconsistent with which joystick port they use?

Forward and backward integration -- cause of errors

Does revoking a certificate result in revocation of its key?

I unknowingly submitted plagiarised work

How to prevent bad sectors?

Windows 10 Programms start without visual Interface

What is the largest (size) solid object ever dropped from an airplane to impact the ground in freefall?

A Python Blackjack terminal based game

What is the object moving across the ceiling in this stock footage?

Why is desire the root of suffering?

Employer asking for online access to bank account - Is this a scam?

Placing bypass capacitors after VCC reaches the IC

Were pens caps holes designed to prevent death by suffocation if swallowed?

Why were helmets and other body armour not commonplace in the 1800s?

How can people dance around bonfires on Lag Lo'Omer - it's darchei emori?



How to use an if/elif inside a class when you need different parameters?


What is the difference between old style and new style classes in Python?How do you test that a Python function throws an exception?How do you split a list into evenly sized chunks?How do you change the size of figures drawn with matplotlib?Difference between abstract class and interface in PythonHow do you remove duplicates from a list whilst preserving order?How can you profile a Python script?How do you read from stdin?How to make a class JSON serializableHow do you append to a file in Python?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm doing a class to put inside all commands about keyboard of pygame, at least all that I need, but when I use if or else being equals to a "variable" I want to define later, it returns a error telling me it isn't defined.



I do not know enough to say in technical therms, sorry by mistakes. I started using button as a key() argument, and I got the same error, then I tried using __init__() but I can use it yet (not sure how), then I made in this way...



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



I want to use the key function to define button, so I could take it later for every keyboard input instead write it all again each time.










share|improve this question






























    1















    I'm doing a class to put inside all commands about keyboard of pygame, at least all that I need, but when I use if or else being equals to a "variable" I want to define later, it returns a error telling me it isn't defined.



    I do not know enough to say in technical therms, sorry by mistakes. I started using button as a key() argument, and I got the same error, then I tried using __init__() but I can use it yet (not sure how), then I made in this way...



    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



    I want to use the key function to define button, so I could take it later for every keyboard input instead write it all again each time.










    share|improve this question


























      1












      1








      1








      I'm doing a class to put inside all commands about keyboard of pygame, at least all that I need, but when I use if or else being equals to a "variable" I want to define later, it returns a error telling me it isn't defined.



      I do not know enough to say in technical therms, sorry by mistakes. I started using button as a key() argument, and I got the same error, then I tried using __init__() but I can use it yet (not sure how), then I made in this way...



      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



      I want to use the key function to define button, so I could take it later for every keyboard input instead write it all again each time.










      share|improve this question
















      I'm doing a class to put inside all commands about keyboard of pygame, at least all that I need, but when I use if or else being equals to a "variable" I want to define later, it returns a error telling me it isn't defined.



      I do not know enough to say in technical therms, sorry by mistakes. I started using button as a key() argument, and I got the same error, then I tried using __init__() but I can use it yet (not sure how), then I made in this way...



      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



      I want to use the key function to define button, so I could take it later for every keyboard input instead write it all again each time.







      python pygame






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 6:22









      TrebledJ

      4,62531433




      4,62531433










      asked Mar 24 at 6:13









      SmithSmith

      82




      82






















          1 Answer
          1






          active

          oldest

          votes


















          0














          The error message




          name 'K_w' is not defined




          occures, bcause you've forgotten the module namespace.



          The name of the constant is pygame.K_w rather than K_w. The constants are placed in the pygame module namespace.



          Either use the full name of the constant:



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


          or import the pygame constants See pygame.locals



          from pygame.locals import *

          # [...]

          w = control().button(K_w)



          Further the variables w is never defined, because control() does generate the object, but button() doesn't return any value. The method button should return self:



          class control():
          def button(self, button):
          self.button = button
          return self


          But I recommend to implement a constructor in the class control rather than the method button (Of course you can do both):



          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)



          The method key has to return the new value of the parameter axis:



          class control():

          # [...]

          def key(self, axis, speed):
          if event.type == pygame.KEYDOWN:
          if event.key == self.button:
          axis = speed
          return axis

          y1, y2 = 0, 0
          while True:
          for event in pygame.event.get():
          ctrl.exit()
          y1 = w.key(y1, -5)
          y1 = s.key(y1, +5)
          y2 = UP.key(y2, -5)
          Y2 = DOWN.key(y2, +5)





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321202%2fhow-to-use-an-if-elif-inside-a-class-when-you-need-different-parameters%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            The error message




            name 'K_w' is not defined




            occures, bcause you've forgotten the module namespace.



            The name of the constant is pygame.K_w rather than K_w. The constants are placed in the pygame module namespace.



            Either use the full name of the constant:



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


            or import the pygame constants See pygame.locals



            from pygame.locals import *

            # [...]

            w = control().button(K_w)



            Further the variables w is never defined, because control() does generate the object, but button() doesn't return any value. The method button should return self:



            class control():
            def button(self, button):
            self.button = button
            return self


            But I recommend to implement a constructor in the class control rather than the method button (Of course you can do both):



            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)



            The method key has to return the new value of the parameter axis:



            class control():

            # [...]

            def key(self, axis, speed):
            if event.type == pygame.KEYDOWN:
            if event.key == self.button:
            axis = speed
            return axis

            y1, y2 = 0, 0
            while True:
            for event in pygame.event.get():
            ctrl.exit()
            y1 = w.key(y1, -5)
            y1 = s.key(y1, +5)
            y2 = UP.key(y2, -5)
            Y2 = DOWN.key(y2, +5)





            share|improve this answer





























              0














              The error message




              name 'K_w' is not defined




              occures, bcause you've forgotten the module namespace.



              The name of the constant is pygame.K_w rather than K_w. The constants are placed in the pygame module namespace.



              Either use the full name of the constant:



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


              or import the pygame constants See pygame.locals



              from pygame.locals import *

              # [...]

              w = control().button(K_w)



              Further the variables w is never defined, because control() does generate the object, but button() doesn't return any value. The method button should return self:



              class control():
              def button(self, button):
              self.button = button
              return self


              But I recommend to implement a constructor in the class control rather than the method button (Of course you can do both):



              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)



              The method key has to return the new value of the parameter axis:



              class control():

              # [...]

              def key(self, axis, speed):
              if event.type == pygame.KEYDOWN:
              if event.key == self.button:
              axis = speed
              return axis

              y1, y2 = 0, 0
              while True:
              for event in pygame.event.get():
              ctrl.exit()
              y1 = w.key(y1, -5)
              y1 = s.key(y1, +5)
              y2 = UP.key(y2, -5)
              Y2 = DOWN.key(y2, +5)





              share|improve this answer



























                0












                0








                0







                The error message




                name 'K_w' is not defined




                occures, bcause you've forgotten the module namespace.



                The name of the constant is pygame.K_w rather than K_w. The constants are placed in the pygame module namespace.



                Either use the full name of the constant:



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


                or import the pygame constants See pygame.locals



                from pygame.locals import *

                # [...]

                w = control().button(K_w)



                Further the variables w is never defined, because control() does generate the object, but button() doesn't return any value. The method button should return self:



                class control():
                def button(self, button):
                self.button = button
                return self


                But I recommend to implement a constructor in the class control rather than the method button (Of course you can do both):



                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)



                The method key has to return the new value of the parameter axis:



                class control():

                # [...]

                def key(self, axis, speed):
                if event.type == pygame.KEYDOWN:
                if event.key == self.button:
                axis = speed
                return axis

                y1, y2 = 0, 0
                while True:
                for event in pygame.event.get():
                ctrl.exit()
                y1 = w.key(y1, -5)
                y1 = s.key(y1, +5)
                y2 = UP.key(y2, -5)
                Y2 = DOWN.key(y2, +5)





                share|improve this answer















                The error message




                name 'K_w' is not defined




                occures, bcause you've forgotten the module namespace.



                The name of the constant is pygame.K_w rather than K_w. The constants are placed in the pygame module namespace.



                Either use the full name of the constant:



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


                or import the pygame constants See pygame.locals



                from pygame.locals import *

                # [...]

                w = control().button(K_w)



                Further the variables w is never defined, because control() does generate the object, but button() doesn't return any value. The method button should return self:



                class control():
                def button(self, button):
                self.button = button
                return self


                But I recommend to implement a constructor in the class control rather than the method button (Of course you can do both):



                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)



                The method key has to return the new value of the parameter axis:



                class control():

                # [...]

                def key(self, axis, speed):
                if event.type == pygame.KEYDOWN:
                if event.key == self.button:
                axis = speed
                return axis

                y1, y2 = 0, 0
                while True:
                for event in pygame.event.get():
                ctrl.exit()
                y1 = w.key(y1, -5)
                y1 = s.key(y1, +5)
                y2 = UP.key(y2, -5)
                Y2 = DOWN.key(y2, +5)






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 24 at 6:53

























                answered Mar 24 at 6:32









                Rabbid76Rabbid76

                48.4k123557




                48.4k123557





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55321202%2fhow-to-use-an-if-elif-inside-a-class-when-you-need-different-parameters%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                    Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?