Creating Classes
In Python, classes are defined using the
Basic syntax of class:
Example: Creating a simple class
In this example:
Class attribute:
Instance attributes:
The
In Python, classes are defined using the
class keyword. Inside the class, we define attributes and methods.Basic syntax of class:
class ClassName:
# Class attributes and methods
Example: Creating a simple class
class Dog:
# Class attributes (shared by all instances)
species = "Canis familiaris"
# Constructor method to initialize instance attributes
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
# Method to display dog's information
def display_info(self):
print(f"My dog {self.name} is {self.age} years old.")
In this example:
Class attribute:
species is shared by all instances of the class.Instance attributes:
name and age are unique to each instance.The
__init__() method is the constructor that is automatically called when an object is created.Creating Objects (Instances)
Objects are created (instantiated) by calling the class with its required arguments.
Example: Creating an Object
Here,
Objects are created (instantiated) by calling the class with its required arguments.
Example: Creating an Object
dog1 = Dog("Buddy", 4) # Creating an object of the Dog class
dog1.display_info() # Output: My dog Buddy is 4 years old.Here,
dog1 is an instance of the Dog class with its own name and age attributes.Instance Variables and Class Variables
Instance variables are unique to each object. They are defined inside the constructor (
Class variables are shared by all objects of the class. They are defined directly inside the class but outside any method.
Example: Class and Instance Variables
Instance variables are unique to each object. They are defined inside the constructor (
__init__()).Class variables are shared by all objects of the class. They are defined directly inside the class but outside any method.
Example: Class and Instance Variables
class Car:
# Class variable (shared by all instances)
wheels = 4
def __init__(self, model, color):
# Instance variables (unique to each instance)
self.model = model
self.color = color
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
print(car1.model) # Output: Toyota
print(car2.color) # Output: Blue
Methods in Classes
Methods are functions that belong to a class. They are defined inside a class and take
Example: Defining methods
Methods are functions that belong to a class. They are defined inside a class and take
self as the first parameter. This self parameter allows the method to access instance variables and other methods within the class.Example: Defining methods
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
# Method to calculate area
def area(self):
return self.width * self.height
rect1 = Rectangle(10, 5)
print(f"Area of rectangle: {rect1.area()}") # Output: Area of rectangle: 50
The
The
The
Example: Using
self ParameterThe
self keyword refers to the current instance of the class. It is used to access instance variables and methods within the class.The
self parameter must be the first parameter of any method in the class.Example: Using
selfclass Circle:
def __init__(self, radius):
self.radius = radius
def circumference(self):
return 2 * 3.1416 * self.radius
circle1 = Circle(7)
print(f"Circumference of circle: {circle1.circumference()}") # Output: 43.9824
Modifying and Accessing Attributes
You can modify and access attributes directly or through methods.
Example: Modifying Attributes
You can modify and access attributes directly or through methods.
Example: Modifying Attributes
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def update_grade(self, new_grade):
self.grade = new_grade
student1 = Student("Alice", "A")
student1.update_grade("B")
print(f"{student1.name} has a grade of {student1.grade}.") # Output: Alice has a grade of B.
Inheritance
Inheritance allows one class (child class) to inherit attributes and methods from another class (parent class). This allows code reuse and the creation of more specific classes from a general class.
Syntax of Inheritance:
Example: Inheritance
In this example, the
Inheritance allows one class (child class) to inherit attributes and methods from another class (parent class). This allows code reuse and the creation of more specific classes from a general class.
Syntax of Inheritance:
class ParentClass:
# Parent class code
class ChildClass(ParentClass):
# Child class code (inherits from ParentClass)
Example: Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
class Dog(Animal): # Dog inherits from Animal
def speak(self):
print(f"{self.name} barks.")
dog1 = Dog("Buddy")
dog1.speak() # Output: Buddy barks.
In this example, the
Dog class inherits from the Animal class and overrides the speak() method.π1
Method Overriding
When a method in a subclass has the same name as a method in the parent class, the method in the subclass overrides the method in the parent class. This allows the child class to modify or extend the behavior of the parent class method.
Example: Method Overriding
When a method in a subclass has the same name as a method in the parent class, the method in the subclass overrides the method in the parent class. This allows the child class to modify or extend the behavior of the parent class method.
Example: Method Overriding
class Animal:
def speak(self):
print("Animal makes a sound.")
class Cat(Animal):
def speak(self):
print("Cat meows.")
cat1 = Cat()
cat1.speak() # Output: Cat meows.
π2
Day 14: Object-Oriented Programming (OOP) - Part 2: Inheritance and Polymorphism
Welcome to Day 14 of the "Noob to Pro in Python" course! Yesterday, we explored the basics of Object-Oriented Programming (OOP), covering classes, objects, methods, and attributes. Today, we will dive deeper into OOP, focusing on inheritance and polymorphismβtwo powerful concepts that enable code reuse and flexibility.
Welcome to Day 14 of the "Noob to Pro in Python" course! Yesterday, we explored the basics of Object-Oriented Programming (OOP), covering classes, objects, methods, and attributes. Today, we will dive deeper into OOP, focusing on inheritance and polymorphismβtwo powerful concepts that enable code reuse and flexibility.
Inheritance in Python
Inheritance allows a class (called a child class or subclass) to inherit attributes and methods from another class (called a parent class or superclass). This promotes code reuse and logical class relationships.
Example: Inheritance Syntax
In this example:
The
The
Inheritance allows a class (called a child class or subclass) to inherit attributes and methods from another class (called a parent class or superclass). This promotes code reuse and logical class relationships.
Example: Inheritance Syntax
class Parent:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} is speaking.")
# Child class inheriting from Parent class
class Child(Parent):
def play(self):
print(f"{self.name} is playing.")
# Creating an object of the Child class
child1 = Child("Alice")
child1.speak() # Inherited method from Parent class
child1.play() # Child class method
In this example:
The
Child class inherits the speak() method from the Parent class.The
Child class also has its own method, play().The
The
Example: Using
Here, the
super() FunctionThe
super() function allows a child class to call the constructor or methods of its parent class. This is useful when you want to extend the functionality of a parent class without duplicating code.Example: Using
super()class Animal:
def __init__(self, species):
self.species = species
def sound(self):
print("Some generic animal sound.")
# Child class inheriting from Animal class
class Dog(Animal):
def __init__(self, name, species="Dog"):
super().__init__(species) # Calling parent class constructor
self.name = name
def sound(self):
super().sound() # Calling parent class method
print(f"{self.name} barks!")
dog1 = Dog("Buddy")
dog1.sound()
Here, the
super() function calls the parent classβs __init__() method to initialize the species attribute and also calls the parent class's sound() method from the child class.Method Overriding
Method overriding occurs when a subclass defines a method with the same name as a method in its parent class. The subclass's version of the method overrides the parent class's version.
Example: Method Overriding
In this example, the
Method overriding occurs when a subclass defines a method with the same name as a method in its parent class. The subclass's version of the method overrides the parent class's version.
Example: Method Overriding
class Animal:
def sound(self):
print("Some generic animal sound.")
class Dog(Animal):
def sound(self):
print("Bark!")
class Cat(Animal):
def sound(self):
print("Meow!")
dog = Dog()
cat = Cat()
dog.sound() # Output: Bark!
cat.sound() # Output: Meow!
In this example, the
sound() method is overridden in the Dog and Cat classes, replacing the generic version from the Animal class.π1
Multiple Inheritance
Python supports multiple inheritance, where a class can inherit from more than one parent class. This allows a class to inherit features from multiple classes.
Example: Multiple Inheritance
In this example, the
Python supports multiple inheritance, where a class can inherit from more than one parent class. This allows a class to inherit features from multiple classes.
Example: Multiple Inheritance
class Father:
def work(self):
print("Father is working.")
class Mother:
def cook(self):
print("Mother is cooking.")
class Child(Father, Mother):
def play(self):
print("Child is playing.")
child = Child()
child.work() # Inherited from Father class
child.cook() # Inherited from Mother class
child.play() # Child's own method
In this example, the
Child class inherits methods from both the Father and Mother classesPolymorphism in Python
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It is implemented through method overriding, where different classes provide their own implementation of a method with the same name.
Example: Polymorphism
Here, both the
Polymorphism allows objects of different classes to be treated as objects of a common superclass. It is implemented through method overriding, where different classes provide their own implementation of a method with the same name.
Example: Polymorphism
class Bird:
def fly(self):
print("Bird is flying.")
class Airplane:
def fly(self):
print("Airplane is flying.")
def take_off(flying_object):
flying_object.fly()
bird = Bird()
airplane = Airplane()
take_off(bird) # Output: Bird is flying.
take_off(airplane) # Output: Airplane is flying.
Here, both the
Bird and Airplane classes have a fly() method, but the behavior is different for each class. The function take_off() can accept either a Bird or an Airplane and call their respective fly() method.π2
The
The
Example:
Example:
isinstance() and issubclass() FunctionsThe
isinstance() function checks if an object is an instance of a class or a subclass, while issubclass() checks if a class is a subclass of another class.Example:
isinstance()class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, Animal)) # Output: True
Example:
issubclass()class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal)) # Output: True
Homework for Day 14
Create a class
Create a class
Employee with attributes name and salary. Create a subclass Manager that inherits from Employee and adds an attribute department. Use super() to initialize the parent class attributes in the subclass.Summary
In Day 14, we covered:
Inheritance, which allows a class to inherit properties and methods from another class, promoting code reuse.
The
Method overriding, which allows a child class to provide a specific implementation of a method that exists in its parent class.
Polymorphism, which allows objects of different classes to be treated as objects of a common superclass.
Multiple inheritance, where a class can inherit from more than one parent class.
Mastering inheritance and polymorphism allows you to write flexible, reusable, and maintainable code. These are powerful features in Pythonβs OOP model, and practicing them will help you build more structured applications. Keep experimenting with these concepts in your exercises and homework!
In Day 14, we covered:
Inheritance, which allows a class to inherit properties and methods from another class, promoting code reuse.
The
super() function, which allows a child class to call methods from its parent class.Method overriding, which allows a child class to provide a specific implementation of a method that exists in its parent class.
Polymorphism, which allows objects of different classes to be treated as objects of a common superclass.
Multiple inheritance, where a class can inherit from more than one parent class.
Mastering inheritance and polymorphism allows you to write flexible, reusable, and maintainable code. These are powerful features in Pythonβs OOP model, and practicing them will help you build more structured applications. Keep experimenting with these concepts in your exercises and homework!
π2π2
Day 15: Encapsulation, Abstraction, and Properties in OOP
Welcome to Day 15 of the "Noob to Pro in Python" course! Today, we will explore two other essential concepts in Object-Oriented Programming (OOP): Encapsulation and Abstraction. These concepts help to hide the internal workings of a class, provide controlled access to data, and enhance the security and maintainability of your code. We'll also cover how to use properties to manage attribute access.
Welcome to Day 15 of the "Noob to Pro in Python" course! Today, we will explore two other essential concepts in Object-Oriented Programming (OOP): Encapsulation and Abstraction. These concepts help to hide the internal workings of a class, provide controlled access to data, and enhance the security and maintainability of your code. We'll also cover how to use properties to manage attribute access.
Encapsulation
Encapsulation is the concept of bundling data (attributes) and methods that operate on that data within a class and restricting direct access to some of the classβs components. This helps protect the objectβs internal state and prevents outside interference.
Encapsulation in Python is achieved by making attributes private using name mangling. In Python, you can indicate that an attribute is private by prefixing its name with a double underscore
Example: Encapsulation with Private Attributes
Here,
Encapsulation is the concept of bundling data (attributes) and methods that operate on that data within a class and restricting direct access to some of the classβs components. This helps protect the objectβs internal state and prevents outside interference.
Encapsulation in Python is achieved by making attributes private using name mangling. In Python, you can indicate that an attribute is private by prefixing its name with a double underscore
__.Example: Encapsulation with Private Attributes
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
def get_balance(self):
return self.__balance
# Creating an object
account = BankAccount(1000)
# Trying to access the private attribute directly
# print(account.__balance) # This will raise an AttributeError
# Using public methods to interact with the balance
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # Output: 1300
Here,
__balance is a private attribute. It cannot be accessed directly from outside the class, but we can interact with it using public methods like deposit(), withdraw(), and get_balance().