0

when I tried to run this code , I got an error

class Pizza:
    def __init__(self, name):
        self.name= name

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

    @name.setter
    def name(self,name):
         print(self.name)

pizza = Pizza(["cheese", "tomato"])

the error :

RuntimeError: maximum recursion depth exceeded

But when I changed the code by making (name) private ,it works fine !

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

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

    @name.setter
    def name(self,name):
        print(self.name)
pizza = Pizza(["cheese", "tomato"])

why I got an error at first , and why it fixed when I make (name) private ?

user2357112
  • 260,549
  • 28
  • 431
  • 505
maysara
  • 5,873
  • 2
  • 23
  • 34

1 Answers1

0

Coming from other languages, its hard to grasp that python doesn't need getters and setters (unless you decide to name the instance variables differently).

For example, you can access that "property" directly since there isn't really the concept of pure encapsulation.

class Pizza:
    def __init__(self, name):
        self.name = name

pizza = Pizza(["cheese", "tomato"])
print(pizza.name)  # ["cheese", "tomato"]
pizza.name = "garlic"
print(pizza.name)  # garlic
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245