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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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)) |
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:
1 2 3 4 5 6 | Eric says: Hello Eric is 8 Ryan says: Hello Ryan is 6 True False |
Eric says: Hello Eric is 8 Ryan says: Hello Ryan is 6 True False
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last 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