Object-oriented Programming#
Structure of object-oriented programming#
Classes#
User-defined data types
Blueprint for objects, attributes, and methods
Let’s define a class
Person
with the attributesage
andname
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Objects#
Instance of a class with specifically defined data
Can correspond to real-world objects
Let’s create an instance of the class
Person
:
p = Person(age=29, name="Veit")
Methods#
Functions that objects can perform
Describe behaviors of an object
Defined inside the class
Let’s add a method that determines if the person is an adult:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def is_adult(self):
return self.age >= 18
Attributes#
Represent state of an object
Defined inside the class
Let’s print the attributes of the instance
p
:
print(p.name) # Output: Veit
print(p.age) # Output: 29
Inheritance and composition#
Inheritance#
Inheritance lets one class reuse or extend the behavior of another class
You create a child class (derived class) that inherits attributes and methods from a parent class (base class)
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof!"
dog = Dog()
print(dog.speak()) # Output: Woof!
Dog inherits from Animal and overrides the speak() method
Is a relationship:
Dog
is a specialized version ofAnimal
Composition#
Composition means building complex objects by combining simpler ones
Instead of inheriting, a class has instances of other classes as attributes
This means that a class
Composite
can contain an object of another class asComponent
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
return self.engine.start()
car = Car()
print(car.start()) # Output: Engine started
Car
has anEngine
, and it uses the engine’s method to starthas a relationship:
Car
has a componentEngine