Object-Oriented Programming: A Comprehensive Guide

Object-Oriented Programming: A Comprehensive Guide

I. Creating and Using Classes

Object-oriented programming (OOP) is a fundamental concept in software development, allowing us to create simulations of real-world objects and systems. In this article, we will explore the basics of OOP, including creating and using classes.

Creating a Class

A class is a blueprint for creating objects, and it defines the attributes and methods of those objects. Let’s create a simple class called Dog:

class Dog(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sit(self):
        print(f"{self.name} is sitting now.")

    def roll(self):
        print(f"{self.name} is rolling now.")

Instantiating a Class

To create an instance of the Dog class, we can call the __init__ method with the required parameters:

my_dog = Dog('XiaoHei', 3)
your_dog = Dog('XiaoHuang', 4)

Accessing Attributes and Methods

We can access the attributes and methods of an object by using dot notation:

my_dog.sit()
my_dog.roll()
print(f"My dog is called {my_dog.name}, it's {my_dog.age} years old")

II. Specifying Default Values to Properties or Modifying Attribute Values

When creating a class, we can specify default values for properties or modify attribute values using the __init__ method:

class Car(object):
    def __init__(self, name, model, year):
        self.name = name
        self.model = model
        self.year = year
        self.odometer = 0  # specify default value

    def describe_car(self):
        print(f"{self.name} {self.model} {self.year}")

    def odometer_read(self):
        print(f"This car has {self.odometer} miles on it")

Modifying Attribute Values

We can modify attribute values directly:

my_car = Car('Audi', 'a4', 2016)
my_car.odometer = 100
my_car.odometer_read()

III. Class Inheritance

When writing a class, we don’t always start from scratch. We can use inheritance to create a new class based on an existing one:

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def talk(self):
        print("Person is talking...")

class BlackPerson(Person):
    def __init__(self, name, age, strength):
        super(BlackPerson, self).__init__(name, age)
        self.strength = strength

    def talk(self):
        print("BlackPerson is talking")

    def walk(self):
        print("Person is walking")

IV. Package

A package is a collection of related classes, functions, and variables. We can create a package using the __init__ method:

class Student(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

obj1 = Student('XiaoMing', 18)
obj2 = Student('zww', 24)
print(obj1.name, obj1.age)

V. Static Method

A static method is a method that belongs to a class, not an instance. We can create a static method using the @staticmethod decorator:

class Dog(object):
    def __init__(self, name):
        self.name = name

    @staticmethod
    def eat():
        print(f"{self.name} is eating")

VI. Class Method

A class method is a method that belongs to a class, and it can access class variables. We can create a class method using the @classmethod decorator:

class Dog(object):
    name = "I am a class variable"

    def __init__(self, name):
        self.name = name

    @classmethod
    def eat(cls):
        print(f"{cls.name} is eating")

VII. Properties Method

A properties method is a method that allows us to access an attribute as if it were a property. We can create a properties method using the @property decorator:

class Dog(object):
    def __init__(self, name):
        self.name = name

    @property
    def eat(self):
        print(f"{self.name} is eating")

VIII. Special Member Method

A special member method is a method that is automatically called by Python when an object is created or destroyed. We can create special member methods using the following names:

  • __init__: constructor method
  • __del__: destructor method
  • __doc__: description for the class
  • __module__: module name
  • __class__: class object
  • __dict__: attribute dictionary
  • __base__: base class

Let’s create a class with special member methods:

class Student:
    count = 0

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Student.count += 1

class Teacher(Student):
    def __init__(self, name, age, lesson):
        super(Teacher, self).__init__(name, age)
        self.lesson = lesson

    def t_info(self):
        print(f"My name is {self.name}, I am {self.age} years old, I am your {self.lesson} teacher")

student1 = Student('Kevin', 24)
student2 = Student('Jay', 28)
teacher1 = Teacher('alex', 24, 'English')
teacher1.t_info()
print(f"__doc__:", Student.__doc__)
print(f"__module__:", student1.__module__)
print(f"__class__:", student2.__class__)
print(f"__dict__:", student2.__dict__)
print(f"__base__:", Teacher.__base__)