PYTHON Tutorial
Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of classes and objects. Classes are blueprints that define the characteristics and behaviors of objects, while objects are instances of classes that represent real-world entities.
class MyClass:
# Class attributes (shared by all instances)
shared_attribute = "shared value"
# Constructor (called when an object is created)
def __init__(self, instance_attribute):
# Instance attributes (unique to each instance)
self.instance_attribute = instance_attribute
# Class methods (can be called on the class itself)
@classmethod
def class_method(cls):
print("This is a class method.")
# Instance methods (can be called on instances of the class)
def instance_method(self):
print(f"This is an instance method. Instance attribute: {self.instance_attribute}")
# Create an object of the MyClass class
my_object = MyClass("instance value")
Inheritance allows you to create new classes (child classes) based on existing classes (parent classes), inheriting their attributes and behaviors.
class ChildClass(MyClass):
# Additional attributes and methods specific to the child class
child_attribute = "child value"
def child_method(self):
print("This is a child method.")
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_name(self):
return self.name
def get_salary(self):
return self.salary
# Create an object of the Employee class
employee1 = Employee("John Doe", 50000)
# Access attributes and methods of the object
print(employee1.get_name()) # Output: John Doe
print(employee1.get_salary()) # Output: 50000
Understanding classes and objects is fundamental to OOP in Python. By defining classes, creating objects, and utilizing class methods and instance methods, you can create structured and reusable code that models real-world entities and their behaviors. Inheritance enables code reuse and simplifies the creation of new classes that inherit the characteristics of existing ones.