Python Forum
Python class doesn't invoke setter during __init__, not sure if's not supposed to?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python class doesn't invoke setter during __init__, not sure if's not supposed to?
#1
Hey,

I have a simple class like this:

class Test:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, n_val):
        self._name = str(n_val).capitalize()
I was expecting it to invoke the setter during creation, so the following would return a capitalized name:

    test_cl = Test("jimmy")
    print(test_cl.name)
But the output is still:

Output:
jimmy
Shouldn't the init run the setter and if not, is it possible to have it do so?
Reply
#2
Use self.name = name instead of self._name = name to run the setter.
BashBedlam likes this post
Reply
#3
That works.

Thank you very much.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  question about using setter, getter and _ akbarza 4 687 Dec-28-2023, 09:43 PM
Last Post: deanhystad
  Initiating an attribute in a class __init__: question billykid999 8 1,340 May-02-2023, 09:09 PM
Last Post: billykid999
Question __init__ of Child Class zero_fX0 4 1,722 Mar-22-2023, 05:23 PM
Last Post: deanhystad
  Class Method to Calculate Age Doesn't Work gdbengo 1 1,712 Oct-30-2021, 11:20 PM
Last Post: Yoriz
  Not including a constructor __init__ in the class definition... bytecrunch 3 11,914 Sep-02-2021, 04:40 AM
Last Post: deanhystad
  How to invoke a function with return statement in list comprehension? maiya 4 2,848 Jul-17-2021, 04:30 PM
Last Post: maiya
  why doesn't python look in two directions Kakha 21 6,497 Jan-01-2021, 11:24 PM
Last Post: jefsummers
  How do I reduce the time to Invoke Macro via Python? JaneTan 1 2,136 Dec-28-2020, 06:46 AM
Last Post: buran
  Python IDE doesn't see opencv-python package on my Jetson Nano sadhaonnisa 1 3,351 Oct-11-2020, 01:04 AM
Last Post: Larz60+
  Supposed to print out even numbers DallasPCMan 4 1,970 May-21-2020, 05:50 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020