简体   繁体   中英

Which is the better way to inheritance?

Is there any difference between this:

class Vehicle():
    def __init__(self,  x, y):
        self.y = y
        self.x = x

class Car(Vehicle):
    def __init__(self, x, y):
        Vehicle.__init__(self, x, y)

class Scooter(Vehicle):
    def __init__(self, x, y):
         Vehicle.__init__(self,  x, y)

and this:

class Vehicle():
    def __init__(self,  x, y):
         self.y = y
         self.x = x

class Car(Vehicle):
         pass            

class Scooter(Vehicle):
         pass

Because without def __init__ in child classes I got the same thing, I mean __init__ doesn't provide any effect.

You should't do either of them. The best way to do it is using super .

class Vehicle():
    def __init__(self,  x, y):
        self.y = y
        self.x = x

class Car(Vehicle):
    def __init__(self, x, y):
        super(Car, self).__init__(x, y)
        # super().__init__(x, y) # for python3

Check this blog post by Raymond Hettinger (core python contributor) on why you should be using super

You need __init__ method when you want to do child specific initialisation. Assume your child classes require another argument to be passed to the constructor and is unique to that class, in that case __init__ method is really required.

class Vehicle():
    def __init__(self,  x, y):
        self.y = y
        self.x = x

class Car(Vehicle):
    def __init__(self, x, y, z):
        Vehicle.__init__(self, x, y)
        self.z = z

class Scooter(Vehicle):
    def __init__(self, x, y, z):
         Vehicle.__init__(self,  x, y)
         self.z = z

If you don't provide an __init__ method in the child classes, they will just use the __init__ method defined in their parent class (aka inheritance). In the former case, you are overriding the __init__ method for the child classes but you are simply calling the __init__ method of the parent class. So if you don't do that (like the later case) it will be the same. The later case automatically inherits the __init__ method.

Other ways to write the same thing would be:

class Car(Vehicle): #This is the best way to do it though
   def __init__(self, x, y):
      super()__init__(x, y)

Or

class Car(Vehicle):
   def __init__(self, x, y):
      self.x = x
      self.y = y

TLDR; They are equivalent.

I think this would be best explained with an example.

Now take this scenario:

>Vehicle  ---> Car,Bike,Boat,Aeroplane,Train

>[All are vehicles right]

>Things they have in common would be (say for ex.) **Price** and **Color**

However things they won't have in common would be?

>**Wheels**. The total number of wheels may differ.
>

> Car-4 Bike-2 Boat-0 Aeroplane-(**Not sure**) Train-(**Many I
    guess**?)

But you get the point right? So When I want to just have a Vehicle object I don't want (or I can't tell the number of wheels ) In that case I can initialize only with just price and color

However when I know the specific type of Vehicle say Car now I can __init__ it with number of wheels . Now this is where object specific initializations play a major role.

A full example code of the above sample:

class Vehicle():
    def __init__(self,  x, y):
        self.color = y
        self.price = x
    def Horn(self):
        print("Pommm...Pommmmm!!")

class Car(Vehicle):
    def __init__(self, x, y,wheel):
        Vehicle.__init__(self, x, y)
        self.wheel = "Four Wheels man: 4"

class Scooter(Vehicle):
    def __init__(self, x, y,wheel):
         Vehicle.__init__(self,  x, y)
         self.wheel = "Just Two man : 2"



VehObj = Vehicle("5000$","Black")
VehObj.Horn()
print(VehObj.color,VehObj.price)

#However note this

carObj = Car("5000$","Black",4)
print(carObj.color,carObj.price,carObj.wheel)

#Look at this

sObj = Scooter("5000$","Black",2)
print(sObj.color,sObj.price,sObj.wheel)

Output:

Pommm...Pommmmm!!
Black 5000$
Black 5000$ Four Wheels man: 4
Black 5000$ Just Two man : 2

Hope that cleared you up.

Calling the init method of super class is optional if you don't wont to edit the __init__ method of superclass.

but if you want to edit the superclass method you need custom init

class Vehicle():
    def __init__(self,  x, y):
        self.y = y
        self.x = x


class Car(Vehicle):
    def __init__(self, x, y, z):
        Vehicle.__init__(self, x, y)
        self.z = z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM