Python面向对象

🏠 类的基本定义

class Mobile:
    def __init__(self):
        print("Inside the Mobile constructor")
        self.brand = None
        brand = "Apple"  # 这是局部变量,不是属性

mob1 = Mobile()
print(mob1.brand)  # None

🔒 私有属性

class Customer:
    def __init__(self, cust_id, name, age, wallet_balance):
        self.cust_id = cust_id
        self.name = name
        self.age = age
        self.__wallet_balance = wallet_balance  # 私有属性

    def update_balance(self, amount):
        if amount < 1000 and amount > 0:
            self.__wallet_balance += amount

    def show_balance(self):
        print("The balance is", self.__wallet_balance)

c1 = Customer(100, "Gopal", 24, 1000)
# print(c1.__wallet_balance)  # 报错,无法访问私有变量

访问私有属性(不推荐)

c1._Customer__wallet_balance = 10000000000
c1.show_balance()

📊 静态变量

class Mobile:
    discount = 50  # 静态变量
    
    def __init__(self, price, brand):
        self.price = price
        self.brand = brand

    def purchase(self):
        total = self.price - self.price * Mobile.discount / 100
        print(self.brand, "mobile with price", self.price, "is available after discount at", total)

mob1 = Mobile(20000, "Apple")
mob1.purchase()
print(Mobile.discount)  # 50
Mobile.discount = 100   # 修改静态变量

🔧 静态方法

class MyClass:
    __my_static_var = "Hello, World!"

    @staticmethod
    def my_static_method():
        print(MyClass.__my_static_var)

# 调用静态方法(不需要实例化)
MyClass.my_static_method()

🏷️ @property装饰器

class Student(object):
    @property
    def birth(self):
        if self._birth < 50:
            return 1
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def age(self):
        return 2015 - self._birth

s = Student()
s.birth = 60
print(s.birth)  # 60

📝 __str__方法

class Shoe:
    def __init__(self, price, material):
        self.price = price
        self.material = material

    def __str__(self):
        return "Shoe with price: " + str(self.price) + " and material: " + self.material

s1 = Shoe(1000, "Canvas")
print(s1)  # Shoe with price: 1000 and material: Canvas

🔄 引用传递

class Mobile:
    def __init__(self, price, brand):
        self.price = price
        self.brand = brand

mob1 = Mobile(1000, "Apple")
mob2 = mob1  # 引用传递

mob2.price = 3000
print("Price of mobile 1:", mob1.price)  # 3000
print("Price of mobile 2:", mob2.price)  # 3000

📦 封装

class Mobile:
    def __init__(self, brand, price):
        self.brand = brand
        self.price = price

    def purchase(self):
        if self.price > 20000:
            print("Price is too high, no discount provided")
        else:
            print("Discount is available")

👨‍👦 继承

class Vehicle:
    def __init__(self, color, maxSpeed):
        self.color = color
        self.maxSpeed = maxSpeed

class Car(Vehicle):
    def __init__(self, color, maxSpeed, numGears, isConvertible):
        super().__init__(color, maxSpeed)
        self.numGears = numGears
        self.isConvertible = isConvertible

    def printCar(self):
        print("Color:", self.color)
        print("MaxSpeed:", self.maxSpeed)
        print("NumGears:", self.numGears)
        print("IsConvertible:", self.isConvertible)

c = Car("red", 15, 3, False)
c.printCar()

👨‍👩‍👦 多继承

class Mother:
    mothername = ""
    def mother(self):
        print(self.mothername)

class Father:
    fathername = ""
    def father(self):
        print(self.fathername)

class Son(Mother, Father):
    def parents(self):
        print("Father:", self.fathername)
        print("Mother:", self.mothername)

s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

🎭 多态

class Vehicle:
    def __init__(self, color):
        self.color = color

class Car(Vehicle):
    def __init__(self, color, numGears):
        super().__init__(color)
        self.numGears = numGears

    def run(self):
        print("Car Color:", self.color)
        print("NumGears:", self.numGears)

class Bike(Vehicle):
    def __init__(self, color):
        super().__init__(color)

    def run(self):
        print("Bike Color:", self.color)

c = Car("black", 5)
b = Bike("red")

for i in [c, b]:
    i.run()  # 多态,相同的函数名有不同的执行结果

🔍 反射查找子类

import inspect

# 获取所有已导入模块中的类
classes = inspect.getmembers(
    inspect.getmodule(inspect.currentframe()),
    lambda member: inspect.isclass(member) and member.__module__ == __name__
)

# 找出所有继承 Vehicle 的子类
vehicle_subclasses = [
    cls for name, cls in classes if issubclass(cls, Vehicle) and cls is not Vehicle
]

作者:spike

分类: Python

创作时间:2026-02-23

更新时间:2026-02-23