Coding in Python: a comprehensive Beginners Guide to Learn the Realms of Coding in Python


Download 1.25 Mb.
Pdf ko'rish
bet41/48
Sana30.01.2023
Hajmi1.25 Mb.
#1140552
1   ...   37   38   39   40   41   42   43   44   ...   48
Bog'liq
Coding in Python A Comprehensive Beginners Guide to Learn the Realms

Child Class in Python 2.7
If you are using Python 2.7, the child class will appear to be a bit different.
See the following code and note the difference.
class Bike():
"""This class will build the model of a bike."""
def __init__(self, bmodel, bmake, bcolor, byear):
self.bmodel = bmodel
self.bmake = bmake
self.bcolor = bcolor
self.byear = byear
self.odometer_reading = 0
def fullname(self):
fullbikename = "We have a bike that hit the markets in " +
str(self.byear) + ". The model is " + self.bmodel + ". The bike is
manufactured by " + self.bmake + ". Its color is " + self.bcolor + "."
return fullbikename.title()
def reading_odometer(self):
print("This bike has run " + str(self.odometer_reading) + " kilometers
on the road.")
def updating_the_odometer(self, bmileage):
self.odometer_reading = bmileage
if bmileage >= self.odometer_reading:


self.odometer_reading = bmileage
else:
print("You are not authorized to roll back the reading of the
odometer.")
def incrementing_odometer(self, bmileage):
self.odometer_reading += bmileage
class RacerBike(Bike):
def __init__(self, bmodel, bmake, bcolor, byear):
super(RacerBike,self).__init__(bmodel, bmake, bcolor, byear)
racer1 = RacerBike('URS: Gravel Riding', 'BMC', 'Grey', '2017')
print(racer1.fullname())
racer2 = RacerBike('Trackmachine', 'BMC', 'Blue', '2015')
print(racer2.fullname())
racer3 = RacerBike('Alpenchallenge', 'BMC', 'Red', '2012')
print(racer2.fullname())
The only change I made was in the super function. I filled in the parenthesis
with the name of the child class and self-parameter. An interesting thing is
that this change does not affect the result of the program, no matter if you do
it in Python 3 or 2.7. However, the former technique will not work in 2.7.
You can see the result of the program as under:
= RESTART: C:/Users/saifia computers/Desktop/sample.py
We Have A Bike That Hit The Markets In 2017. The Model Is Urs: Gravel
Riding. The Bike Is Manufactured By Bmc. Its Color Is Grey.
We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
We Have A Bike That Hit The Markets In 2015. The Model Is
Trackmachine. The Bike Is Manufactured By Bmc. Its Color Is Blue.
>>>



Download 1.25 Mb.

Do'stlaringiz bilan baham:
1   ...   37   38   39   40   41   42   43   44   ...   48




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling