How to use *args and self in Python constructorWhat does ** (double star/asterisk) and * (star/asterisk) do for parameters?How do I check whether a file exists without exceptions?Calling an external command in PythonWhat are metaclasses in Python?How can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonWhat is a clean, pythonic way to have multiple constructors in Python?Use of *args and **kwargsDoes Python have a string 'contains' substring method?Creating a singleton in Python

Why did the Mercure fail?

If a character has darkvision, can they see through an area of nonmagical darkness filled with lightly obscuring gas?

Start making guitar arrangements

Why electric field inside a cavity of a non-conducting sphere not zero?

How could a planet have erratic days?

What does routing an IP address mean?

What should you do if you miss a job interview (deliberately)?

Create all possible words using a set or letters

Should I stop contributing to retirement accounts?

Creature in Shazam mid-credits scene?

What is the evidence for the "tyranny of the majority problem" in a direct democracy context?

Is the U.S. Code copyrighted by the Government?

Store Credit Card Information in Password Manager?

Does a 'pending' US visa application constitute a denial?

Is it improper etiquette to ask your opponent what his/her rating is before the game?

Aragorn's "guise" in the Orthanc Stone

Is there a single word describing earning money through any means?

What was the exact wording from Ivanhoe of this advice on how to free yourself from slavery?

Melting point of aspirin, contradicting sources

Closed-form expression for certain product

Lowest total scrabble score

What does chmod -u do?

Is it possible to have a strip of cold climate in the middle of a planet?

Problem with TransformedDistribution



How to use *args and self in Python constructor


What does ** (double star/asterisk) and * (star/asterisk) do for parameters?How do I check whether a file exists without exceptions?Calling an external command in PythonWhat are metaclasses in Python?How can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonWhat is a clean, pythonic way to have multiple constructors in Python?Use of *args and **kwargsDoes Python have a string 'contains' substring method?Creating a singleton in Python













-2















I need a Python method to have access to self for instance variables and also be able to take any number of arguments. I basically want a method foo that can be called via



foo(a, b, c)


or



foo()


In the class, I think the constructor would be



def foo(self, *args):


Is this correct? Also, fyi, I am new to Python (if you can't tell).










share|improve this question

















  • 1





    Possible duplicate of What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

    – alec935
    Mar 8 at 4:57















-2















I need a Python method to have access to self for instance variables and also be able to take any number of arguments. I basically want a method foo that can be called via



foo(a, b, c)


or



foo()


In the class, I think the constructor would be



def foo(self, *args):


Is this correct? Also, fyi, I am new to Python (if you can't tell).










share|improve this question

















  • 1





    Possible duplicate of What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

    – alec935
    Mar 8 at 4:57













-2












-2








-2








I need a Python method to have access to self for instance variables and also be able to take any number of arguments. I basically want a method foo that can be called via



foo(a, b, c)


or



foo()


In the class, I think the constructor would be



def foo(self, *args):


Is this correct? Also, fyi, I am new to Python (if you can't tell).










share|improve this question














I need a Python method to have access to self for instance variables and also be able to take any number of arguments. I basically want a method foo that can be called via



foo(a, b, c)


or



foo()


In the class, I think the constructor would be



def foo(self, *args):


Is this correct? Also, fyi, I am new to Python (if you can't tell).







python args






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 4:42









Intrastellar ExplorerIntrastellar Explorer

717




717







  • 1





    Possible duplicate of What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

    – alec935
    Mar 8 at 4:57












  • 1





    Possible duplicate of What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

    – alec935
    Mar 8 at 4:57







1




1





Possible duplicate of What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

– alec935
Mar 8 at 4:57





Possible duplicate of What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

– alec935
Mar 8 at 4:57












3 Answers
3






active

oldest

votes


















1














You just have to add it after the self parameter:



class YourClass:
def foo(self, *args):
print(args)
def bar(self, *args, **kwargs):
print(args)
print(kwargs)
def baz(self, **kwargs):
print(kwargs)


I have also added a method in which you also add **kwargs, and the case in which you add both *args and **kwargs.



Examples



>>> o = YourClass()
>>> o.foo()
()
>>> o.foo(1)
(1,)
>>> o.foo(1, 2)
(1, 2)





share|improve this answer
































    1














    def foo(self, *args):


    Yes, that is correct.






    share|improve this answer
































      1














      You declared the method correctly. You can also use double asterisks to accept keyword arguments.
      Reference: Expressions




      A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.



      ....



      An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.




      Args will be a tuple. To access the values you will have to iterate or use positional arguments, ie: args[0]






      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%2f55056846%2fhow-to-use-args-and-self-in-python-constructor%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        You just have to add it after the self parameter:



        class YourClass:
        def foo(self, *args):
        print(args)
        def bar(self, *args, **kwargs):
        print(args)
        print(kwargs)
        def baz(self, **kwargs):
        print(kwargs)


        I have also added a method in which you also add **kwargs, and the case in which you add both *args and **kwargs.



        Examples



        >>> o = YourClass()
        >>> o.foo()
        ()
        >>> o.foo(1)
        (1,)
        >>> o.foo(1, 2)
        (1, 2)





        share|improve this answer





























          1














          You just have to add it after the self parameter:



          class YourClass:
          def foo(self, *args):
          print(args)
          def bar(self, *args, **kwargs):
          print(args)
          print(kwargs)
          def baz(self, **kwargs):
          print(kwargs)


          I have also added a method in which you also add **kwargs, and the case in which you add both *args and **kwargs.



          Examples



          >>> o = YourClass()
          >>> o.foo()
          ()
          >>> o.foo(1)
          (1,)
          >>> o.foo(1, 2)
          (1, 2)





          share|improve this answer



























            1












            1








            1







            You just have to add it after the self parameter:



            class YourClass:
            def foo(self, *args):
            print(args)
            def bar(self, *args, **kwargs):
            print(args)
            print(kwargs)
            def baz(self, **kwargs):
            print(kwargs)


            I have also added a method in which you also add **kwargs, and the case in which you add both *args and **kwargs.



            Examples



            >>> o = YourClass()
            >>> o.foo()
            ()
            >>> o.foo(1)
            (1,)
            >>> o.foo(1, 2)
            (1, 2)





            share|improve this answer















            You just have to add it after the self parameter:



            class YourClass:
            def foo(self, *args):
            print(args)
            def bar(self, *args, **kwargs):
            print(args)
            print(kwargs)
            def baz(self, **kwargs):
            print(kwargs)


            I have also added a method in which you also add **kwargs, and the case in which you add both *args and **kwargs.



            Examples



            >>> o = YourClass()
            >>> o.foo()
            ()
            >>> o.foo(1)
            (1,)
            >>> o.foo(1, 2)
            (1, 2)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 4:52

























            answered Mar 8 at 4:46









            lmiguelvargasflmiguelvargasf

            12.9k1388112




            12.9k1388112























                1














                def foo(self, *args):


                Yes, that is correct.






                share|improve this answer





























                  1














                  def foo(self, *args):


                  Yes, that is correct.






                  share|improve this answer



























                    1












                    1








                    1







                    def foo(self, *args):


                    Yes, that is correct.






                    share|improve this answer















                    def foo(self, *args):


                    Yes, that is correct.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    answered Mar 8 at 4:43


























                    community wiki





                    John Kugelman






















                        1














                        You declared the method correctly. You can also use double asterisks to accept keyword arguments.
                        Reference: Expressions




                        A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.



                        ....



                        An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.




                        Args will be a tuple. To access the values you will have to iterate or use positional arguments, ie: args[0]






                        share|improve this answer



























                          1














                          You declared the method correctly. You can also use double asterisks to accept keyword arguments.
                          Reference: Expressions




                          A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.



                          ....



                          An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.




                          Args will be a tuple. To access the values you will have to iterate or use positional arguments, ie: args[0]






                          share|improve this answer

























                            1












                            1








                            1







                            You declared the method correctly. You can also use double asterisks to accept keyword arguments.
                            Reference: Expressions




                            A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.



                            ....



                            An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.




                            Args will be a tuple. To access the values you will have to iterate or use positional arguments, ie: args[0]






                            share|improve this answer













                            You declared the method correctly. You can also use double asterisks to accept keyword arguments.
                            Reference: Expressions




                            A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.



                            ....



                            An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.




                            Args will be a tuple. To access the values you will have to iterate or use positional arguments, ie: args[0]







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 8 at 4:57









                            ap288ap288

                            365




                            365



























                                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%2f55056846%2fhow-to-use-args-and-self-in-python-constructor%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

                                Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                                Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme