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

                                Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                                Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                                How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page