xxddd_69
xxddd_69

Reputation: 83

python derived class constructor

a very dumb question, if we write __init__(self, ..) in our derived class then the derived class will no longer inherit the parent class's constructor because we overwrite it, if we want to keep using the constructor from the parent class we need to write parentClass.__init__(self, ..). However I noticed it is not true

class Item:
    def __init__(self,name= '',quantity = 0):
        self.name = name
        self.quantity = quantity

    def set_name(self, nm):
        self.name = nm

    def set_quantity(self, qnty):
        self.quantity = qnty

    def display(self):
        print(self.name, self.quantity)


class Produce(Item):  # Derived from Item
    def __init__(self,expiration = ''):
        self.expiration = expiration

    def set_expiration(self, expir):
        self.expiration = expir

    def get_expiration(self):
        return self.expiration

item2 = Produce()
item2.set_name('Apples')
item2.set_quantity(40)
item2.set_expiration('May 5, 2012')

print(item2.name,item2.quantity)

I can still access the parent class' attribute name and quantity without using Item.__init__(self) Could someone give me some hints why it works? Thanks in advance

Upvotes: 0

Views: 47

Answers (1)

Jiří Baum
Jiří Baum

Reputation: 6930

The name and quantity are created in your set_...() methods.

In python, any method can create attributes on a class; it's usually considered bad style to do so, but there's no problem doing it - the only concern is that it can be confusing.

BTW, speaking of style - in python it's usually better style to omit setters and use item2.name = 'Apples' rather than item2.set_name('Apples'). If a setter is needed later, name can be turned into a property, overriding what happens on item2.name = 'Apples'

Upvotes: 2

Related Questions