Teaching Kids Programming: Videos on Data Structures and Algorithms
Object Oriented Programming (OOP) is an important programming design paradigm. We model data in classes and objects. Class is the object template where object is the instance of a Class. In this tutorial, we are going to look at using Python to create a Class Person, and a Class Car. And then, we are going to create two Persons: Eric and Ryan, also a car object Audi.
We can invoke the methods on objects using the dot operator. We use the __init__ to define a constructor which is used when creating/initialising the object. The first parameter needs to be self so that we know it belongs to the object.
We can use self.name in a constructor to declare the attributes of a class/object. We use function isinstance(a, b) to check if Object a is an instance of Class b.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def sayHello(self, msg):
print(self.name + " says: " + msg)
def howOld(self):
print(self.name + " is " + str(self.age))
class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def speed(self):
return self.speed
Eric = Person("Eric", 8)
Ryan = Person("Ryan", 6)
Eric.sayHello("Hello")
Eric.howOld()
Ryan.sayHello("Hello")
Ryan.howOld()
Audi = Car("Audi", 100)
print(isinstance(Eric, Person))
print(isinstance(Audi, Person))
This prints the following:
Eric says: Hello
Eric is 8
Ryan says: Hello
Ryan is 6
True
False
–EOF (The Ultimate Computing & Technology Blog) —
342 wordsLast Post: Breadth First Search Algorithm to Convert Level Order Binary Search Tree to Linked List
Next Post: Algorithms to Compute the Difference of Two Maps