Foundations of Python

You are currently auditing this course.
128 / 134

Python Classes and Objects

Overview

As part of this session, we will learn the following:

  1. What is a Class?
  2. What are objects?
  3. What are the methods and attributes?
  4. A simple example of a class in Python
  5. dir() and type() functions
  6. Using the dir() function on strings
  7. Object Lifecycle
  8. What are constructors in a Class?
  9. What is Inheritance?
  10. How do we inherit a class in Python?

Recording of Session


Slides

Code Repository for the course on GitHub


Example of Mulitple Inheritance

class Vehicle:
    #dunder
    def __init__(self, color, make, model="Good"):
        self.color = color
        self.make = make
        self.model = model
        self.speed = 0
        #self.drag = 0

    def __repr__(self):
        return "My vehicle is:" + self.color + ":" + self.make + ":" + str(self.speed)

    def run(self, speed):
        self.speed = speed

veh1 = Vehicle("Red", "Toyota", "Corrola")
print(veh1)
print(veh1.color)
print(veh1.make)
print(veh1.model)
veh1.run(100)
print(veh1)

myvehs = [
    Vehicle("Red", "Toyota1", "Corrola1"),
    Vehicle("Reds", "Toyota2", "Corrola2"),
    Vehicle("Redd", "Toyota3", "Corrola3"),
    Vehicle("Redd", "Toyota4", "Corrola4")
]

for veh in myvehs:
    print(veh)

class Car(Vehicle):
    drag = 0
    def do_drag(self, drag):
        self.drag = drag

    def __repr__(self):
        return "My car is:" + self.color + ":" + self.make + ":" + " Drag: " + str(self.drag)

car = Car("Red", "Toyota", "Corrola")
print(car)
car.do_drag(90)
print(car)

class CarSports(Car, Vehicle):
    fly = 0
    def do_fly(self, fly):
        self.fly = fly

    def __repr__(self):
        return "My car is:" + self.color + ":" + self.make + ":" + " Drag: " + str(self.drag) \
        + " Fly: " + str(self.fly)

carsports1 = CarSports("Red", "Toyota", "Corrola")
print(carsports1)
carsports1.do_fly(90)
print(carsports1)

No hints are availble for this assesment

Answer is not availble for this assesment

Loading comments...