0

Here is the code:

class Duck():
    def __init__(self,input_name):
        self.__name = input_name

    @property
    def name(self):
        print('inside the getter')
        return self.__name

    @name.setter
    def name(self):
        print('inside the setter')
        self.__name = input_name


fowl = Duck("Howard")

So, "dot" is the connection between object and method. That's to say, type fowl.name will get "Howard", because the object called name and returned self.__name.

My question is if I type fowl.name = "cat", why I won't get anything from @property, getter. And how the program knew it's a setter? Because I used "="?

Asocia
  • 5,935
  • 2
  • 21
  • 46
  • 1
    The short answer is that when you're assigning `fowl.name` using the `=` operator, you're calling the `setattr` of `fowl`, and this triggering the `setter` of `name`. When you instead retrieve the information stored inside of `fowl.name` you're calling the `getattr` of `fowl`, thus triggering the `getter` of `name`. – Hampus Larsson Dec 09 '20 at 20:44
  • 1
    Does this answer your question? [How do Python properties work?](https://stackoverflow.com/questions/6193556/how-do-python-properties-work) – Hampus Larsson Dec 09 '20 at 20:48
  • Yes sir. You answered my question. And thanks for extra link!!! – Szu-Hua Huang Dec 09 '20 at 20:51

0 Answers0