Python Forum

Full Version: Python class doesn't invoke setter during __init__, not sure if's not supposed to?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
Use self.name = name instead of self._name = name to run the setter.
That works.

Thank you very much.