Tom
Tom

Reputation: 301

Variable with underscore definition inside class

class Ticket:
    def __init__(self, price):
        self.price = price
    @property
    def price(self):
        return self._price
    @price.setter
    def price(self, new_price):
        if new_price < 0:
            raise ValueError('Try again')
        self._price = new_price

In the above class definition, self._price is used in both functions of price, but the variable _price is not defined before it is used.

This class works good like

t = Ticket(4)
print(t.price)
t.price = 34

I was wondering how this class works? Where is the variable _price defined?

Upvotes: 2

Views: 69

Answers (1)

user2201041
user2201041

Reputation:

You're right that _price is never defined. But there's no error because this code never tries to access it. The problem is here:

def __init__(self, price):
    self.price = price

This code ends up replacing your getter with the value 4 (or whatever you pass in). We can demonstrate this by adding prints to your getters and setters.

class Ticket:
    def __init__(self, price):
        self.price = price
    @property
    def price(self):
        print('get price')
        return self._price
    @price.setter
    def price(self, new_price):
        print('set price')
        if new_price < 0:
            raise ValueError('Try again')
        self._price = new_price

You will see that nothing is printed.. Change to this...

def __init__(self, price):
    self._price = price

And your getters and setters are now getting called

Upvotes: 1

Related Questions