Python alter attribute of instance during initialization Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?Calling an external command in PythonWhat are metaclasses in Python?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 Python super() with __init__() methodsHow to know if an object has an attribute in PythonProper way to declare custom exceptions in modern Python?Does Python have a string 'contains' substring method?

Sorting numerically

List *all* the tuples!

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

Is there a service that would inform me whenever a new direct route is scheduled from a given airport?

Can a non-EU citizen traveling with me come with me through the EU passport line?

What are the pros and cons of Aerospike nosecones?

What happens to sewage if there is no river near by?

How do I mention the quality of my school without bragging

Why is "Captain Marvel" translated as male in Portugal?

What is the correct way to use the pinch test for dehydration?

Disable hyphenation for an entire paragraph

When to stop saving and start investing?

What's the purpose of writing one's academic bio in 3rd person?

What would be the ideal power source for a cybernetic eye?

Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

How much radiation do nuclear physics experiments expose researchers to nowadays?

How to find all the available tools in macOS terminal?

Should I use Javascript Classes or Apex Classes in Lightning Web Components?

Is the address of a local variable a constexpr?

Why does Python start at index 1 when iterating an array backwards?

Should I discuss the type of campaign with my players?

Are my PIs rude or am I just being too sensitive?

Stars Make Stars

If Jon Snow became King of the Seven Kingdoms what would his regnal number be?



Python alter attribute of instance during initialization



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?Calling an external command in PythonWhat are metaclasses in Python?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 Python super() with __init__() methodsHow to know if an object has an attribute in PythonProper way to declare custom exceptions in modern Python?Does Python have a string 'contains' substring method?



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








-3















Is it possible to alter attributes of instances during its initialization?



E. G the following code.



class Sensor() :
def __init__(self) :
self.name = 'pressure'

Sensor1 = Sensor(name='pH')


Would that be possible?










share|improve this question






























    -3















    Is it possible to alter attributes of instances during its initialization?



    E. G the following code.



    class Sensor() :
    def __init__(self) :
    self.name = 'pressure'

    Sensor1 = Sensor(name='pH')


    Would that be possible?










    share|improve this question


























      -3












      -3








      -3








      Is it possible to alter attributes of instances during its initialization?



      E. G the following code.



      class Sensor() :
      def __init__(self) :
      self.name = 'pressure'

      Sensor1 = Sensor(name='pH')


      Would that be possible?










      share|improve this question
















      Is it possible to alter attributes of instances during its initialization?



      E. G the following code.



      class Sensor() :
      def __init__(self) :
      self.name = 'pressure'

      Sensor1 = Sensor(name='pH')


      Would that be possible?







      python class






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 8 at 16:23









      Carlos Gonzalez

      621718




      621718










      asked Mar 8 at 16:19









      Leo blublaLeo blubla

      156




      156






















          3 Answers
          3






          active

          oldest

          votes


















          3














          You need to explicitly declare you accept a name argument and then you need to explicitly update the appropriate attribute:



          class Sensor():
          def __init__(self, name='pressure'):
          self.name = name


          Notice that I'm using 'pressure' as a default value for the name argument in case the consumer does not provide it:



          a = Sensor()
          print(a.name) # 'pressure'

          b = Sensor(name='sensor')
          print(b.name) # 'sensor'


          name can also be provided as a positional argument:



          c = Sensor('some_name')
          print(c.name) # 'some_name'



          A more generic approach



          There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:



          class Sensor():
          def __init__(self, **kwargs):
          for attr, value in kwargs.items():
          setattr(self, attr, value)


          Then you can do something like:



          d = Sensor(name='foo', temperature=70, active=True)
          print(d.name) # 'foo'
          print(d.temperature) # 70
          print(d.active) # True





          share|improve this answer
































            2














            Not like that, if you want to set the attribute you would have to do something like:



            class Sensor() :
            def __init__(self, name='pressure') :
            self.name = name

            Sensor1 = Sensor(name='pH')


            If not provided the name would be pressure but if name is given in the initialization it will be set to the one provided.






            share|improve this answer
































              1














              You will need to give a way to pass those and set default values. In your example, you just need to add a default.



               class Sensor() :
              def __init__(self,name='pressure') :
              self.name = name





              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%2f55067097%2fpython-alter-attribute-of-instance-during-initialization%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









                3














                You need to explicitly declare you accept a name argument and then you need to explicitly update the appropriate attribute:



                class Sensor():
                def __init__(self, name='pressure'):
                self.name = name


                Notice that I'm using 'pressure' as a default value for the name argument in case the consumer does not provide it:



                a = Sensor()
                print(a.name) # 'pressure'

                b = Sensor(name='sensor')
                print(b.name) # 'sensor'


                name can also be provided as a positional argument:



                c = Sensor('some_name')
                print(c.name) # 'some_name'



                A more generic approach



                There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:



                class Sensor():
                def __init__(self, **kwargs):
                for attr, value in kwargs.items():
                setattr(self, attr, value)


                Then you can do something like:



                d = Sensor(name='foo', temperature=70, active=True)
                print(d.name) # 'foo'
                print(d.temperature) # 70
                print(d.active) # True





                share|improve this answer





























                  3














                  You need to explicitly declare you accept a name argument and then you need to explicitly update the appropriate attribute:



                  class Sensor():
                  def __init__(self, name='pressure'):
                  self.name = name


                  Notice that I'm using 'pressure' as a default value for the name argument in case the consumer does not provide it:



                  a = Sensor()
                  print(a.name) # 'pressure'

                  b = Sensor(name='sensor')
                  print(b.name) # 'sensor'


                  name can also be provided as a positional argument:



                  c = Sensor('some_name')
                  print(c.name) # 'some_name'



                  A more generic approach



                  There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:



                  class Sensor():
                  def __init__(self, **kwargs):
                  for attr, value in kwargs.items():
                  setattr(self, attr, value)


                  Then you can do something like:



                  d = Sensor(name='foo', temperature=70, active=True)
                  print(d.name) # 'foo'
                  print(d.temperature) # 70
                  print(d.active) # True





                  share|improve this answer



























                    3












                    3








                    3







                    You need to explicitly declare you accept a name argument and then you need to explicitly update the appropriate attribute:



                    class Sensor():
                    def __init__(self, name='pressure'):
                    self.name = name


                    Notice that I'm using 'pressure' as a default value for the name argument in case the consumer does not provide it:



                    a = Sensor()
                    print(a.name) # 'pressure'

                    b = Sensor(name='sensor')
                    print(b.name) # 'sensor'


                    name can also be provided as a positional argument:



                    c = Sensor('some_name')
                    print(c.name) # 'some_name'



                    A more generic approach



                    There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:



                    class Sensor():
                    def __init__(self, **kwargs):
                    for attr, value in kwargs.items():
                    setattr(self, attr, value)


                    Then you can do something like:



                    d = Sensor(name='foo', temperature=70, active=True)
                    print(d.name) # 'foo'
                    print(d.temperature) # 70
                    print(d.active) # True





                    share|improve this answer















                    You need to explicitly declare you accept a name argument and then you need to explicitly update the appropriate attribute:



                    class Sensor():
                    def __init__(self, name='pressure'):
                    self.name = name


                    Notice that I'm using 'pressure' as a default value for the name argument in case the consumer does not provide it:



                    a = Sensor()
                    print(a.name) # 'pressure'

                    b = Sensor(name='sensor')
                    print(b.name) # 'sensor'


                    name can also be provided as a positional argument:



                    c = Sensor('some_name')
                    print(c.name) # 'some_name'



                    A more generic approach



                    There's also a more generic approach (if the use cases requires it), which involves creating the attributes dynamically:



                    class Sensor():
                    def __init__(self, **kwargs):
                    for attr, value in kwargs.items():
                    setattr(self, attr, value)


                    Then you can do something like:



                    d = Sensor(name='foo', temperature=70, active=True)
                    print(d.name) # 'foo'
                    print(d.temperature) # 70
                    print(d.active) # True






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 8 at 17:00

























                    answered Mar 8 at 16:28









                    Matias CiceroMatias Cicero

                    13.6k842104




                    13.6k842104























                        2














                        Not like that, if you want to set the attribute you would have to do something like:



                        class Sensor() :
                        def __init__(self, name='pressure') :
                        self.name = name

                        Sensor1 = Sensor(name='pH')


                        If not provided the name would be pressure but if name is given in the initialization it will be set to the one provided.






                        share|improve this answer





























                          2














                          Not like that, if you want to set the attribute you would have to do something like:



                          class Sensor() :
                          def __init__(self, name='pressure') :
                          self.name = name

                          Sensor1 = Sensor(name='pH')


                          If not provided the name would be pressure but if name is given in the initialization it will be set to the one provided.






                          share|improve this answer



























                            2












                            2








                            2







                            Not like that, if you want to set the attribute you would have to do something like:



                            class Sensor() :
                            def __init__(self, name='pressure') :
                            self.name = name

                            Sensor1 = Sensor(name='pH')


                            If not provided the name would be pressure but if name is given in the initialization it will be set to the one provided.






                            share|improve this answer















                            Not like that, if you want to set the attribute you would have to do something like:



                            class Sensor() :
                            def __init__(self, name='pressure') :
                            self.name = name

                            Sensor1 = Sensor(name='pH')


                            If not provided the name would be pressure but if name is given in the initialization it will be set to the one provided.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Mar 8 at 16:32

























                            answered Mar 8 at 16:27









                            Carlos GonzalezCarlos Gonzalez

                            621718




                            621718





















                                1














                                You will need to give a way to pass those and set default values. In your example, you just need to add a default.



                                 class Sensor() :
                                def __init__(self,name='pressure') :
                                self.name = name





                                share|improve this answer



























                                  1














                                  You will need to give a way to pass those and set default values. In your example, you just need to add a default.



                                   class Sensor() :
                                  def __init__(self,name='pressure') :
                                  self.name = name





                                  share|improve this answer

























                                    1












                                    1








                                    1







                                    You will need to give a way to pass those and set default values. In your example, you just need to add a default.



                                     class Sensor() :
                                    def __init__(self,name='pressure') :
                                    self.name = name





                                    share|improve this answer













                                    You will need to give a way to pass those and set default values. In your example, you just need to add a default.



                                     class Sensor() :
                                    def __init__(self,name='pressure') :
                                    self.name = name






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 8 at 16:28









                                    Polkaguy6000Polkaguy6000

                                    693513




                                    693513



























                                        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%2f55067097%2fpython-alter-attribute-of-instance-during-initialization%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

                                        Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                                        Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                                        Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved