再再肝3天,整理了70个Python面向对象编程案例,怎能不收藏?

本文详细梳理了70个Python面向对象编程的案例,涵盖类的创建、方法、装饰器、继承、多态、元类等核心概念,适合进阶学习和收藏。
摘要由CSDN通过智能技术生成

Python 作为一门面向对象编程语言,常用的面向对象知识怎么能不清楚呢,今天就来分享一波

文章很长,高低要忍一下,如果忍不了,那就收藏吧,总会用到的

萝卜哥也贴心的做成了PDF,在文末获取!

在 Python 中创建一个类及其对象

class Employee:
    salary = 10000
    name = "John Doe"
 
 
emp1 = Employee()
print(emp1.salary)
print(emp1.name)

Output:

10000
John Doe

在 Python 中创建一个空类

class Employee:
    pass
 
 
e1 = Employee()
print(e1)
 
e1.name = "John Doe"
print(e1.name)

Output:

<__main__.Employee object at 0x0000000002DA51D0>
John Doe

在 Python 中使用 Type 创建类

e1 = type('Employee', (), {})()
print(e1)
 
e1.name = "John Doe"
print(e1.name)

Output:

<__main__.Employee object at 0x0000000002DCC780>
John Doe

在 Python 中创建和调用类的方法

class Employee:
    salary = 10000
    name = "John Doe"
 
    def tax(self):
        print(self.salary * 0.10)
 
 
emp1 = Employee()
print(emp1.salary)
print(emp1.name)
emp1.tax()

Output:

10000
John Doe
1000.0

使用 init() 方法为数据属性赋值

class Employee:
        def __init__(self, salary, name):
                self.salary = salary
                self.name = name
 
 
emp1 = Employee(10000"John Doe")
print(emp1.salary)
print(emp1.name)

Output:

10000
John Doe

在 Python 中更新对象属性

class Employee:
    def __init__(self, salary, name):
        self.salary = salary
        self.name = name
 
 
emp1 = Employee(10000"John Doe")
print(emp1.salary)
 
emp1.salary = 20000
print(emp1.salary)

Output:

10000
20000

在 Python 中删除对象属性和对象

class Employee:
    def __init__(self, salary, name):
        self.salary = salary
        self.name = name
 
 
emp1 = Employee(10000"John Doe")
 
del emp1.salary     # Delete object property
del emp1            # Delete object

Output:

哈哈

在 Python 中检查和比较对象的类型

class Test(object):
    pass
 
 
print(type(Test))
 
obj1 = Test()
print(type(obj1))
 
obj2 = Test()
print(type(obj1) is type(obj2))

Output:

< class 'type' >
< class '__main__.Test' >
True

在Python中将对象的所有属性复制到另一个对象

class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()
        self.foo = 1
        self.bar = 2
 
 
obj1 = MyClass()
obj2 = MyClass()
 
obj1.foo = 25
obj2.__dict__.update(obj1.__dict__)
 
print(obj1.foo)
print(obj2.foo)

Output:

25
25

在 Python 中迭代对象属性

class A():
    m = 1
    n = 2
 
    def __int__(self, x=1, y=2, z=3):
        self.x = x
        self._y = y
        self.__z__ = z
 
    def xyz(self):
        print(x, y, z)
 
 
obj = A()
print(dir(obj))
print([a for a in dir(obj) if not a.startswith('__')])

Output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm', 'n', 'xyz']
['m', 'n', 'xyz']

在 Python 中打印对象的所有属性

class Animal(object):
    def __init__(self):
        self.eyes = 2
        self.name = 'Dog'
        self.color= 'Spotted'
        self.legs= 4
        self.age  = 10
        self.kids = 0
 
 
animal = Animal()
animal.tail = 1
 
temp = vars(animal)
for item in temp:
    print(item, ':', temp[item])

Output:

kids : 0
eyes : 2
name : Dog
color : Spotted
tail : 1
legs : 4
age : 10

在python中在运行时创建类的数据属性

class Employee:
    pass
 
 
emp1 = Employee()
setattr(emp1, 'Salary'12000)
 
emp2 = Employee()
setattr(emp2, 'Age'25)
 
print(emp1.Salary)
print(emp2.Age)

Output:

12000
25

在函数中将对象的实例作为参数传递

class Vehicle:
    def __init__(self):
        self.trucks = []

    def add_truck(self, truck):
        self.trucks.append(truck)


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

    def __repr__(self):
        return "{}".format(self.color)


def main():
    v = Vehicle()
    for t in 'Red Blue Black'.split():
        t = Truck(t)
        v.add_truck(t)
    print(v.trucks)


if __name__ == "__main__":
    main()

Output:

[Red, Blue, Black]

在 Python 中创建和使用自定义 Self 参数

class Employee:
    def __init__(person, salary, name):
        person.salary = salary
        person.name = name
 
    def print_details(emp):
        print(str(emp.salary) + ' : ' + emp.name)
 
 
emp1 = Employee(10000'John Doe')
emp1.print_details()

Output:

10000 : John Doe

使用self参数来维护对象的状态

class State(object):
    def __init__(self):
        self.field = 5.0
 
    def add(self, x):
        self.field += x
 
    def mul(self, x):
        self.field *= x
 
    def div(self, x):
        self.field /= x
 
    def sub(self, x):
        self.field -= x
 
 
s = State()
print(s.field)
 
s.add(2)         # Self is implicitly passed.
print(s.field)
 
s.mul(2)         # Self is implicitly passed.
print(s.field)
 
s.div(2)         # Self is implicitly passed.
print(s.field)
 
s.sub(2)         # Self is implicitly passed.
print(s.field)

Output:

5.0
7.0
14.0
7.0
5.0

在 Python 中创建和使用静态类变量

class Employee:
    age = 25
 
 
print(Employee.age)
 
e = Employee()
print(e.age)
 
e.age = 30
print(Employee.age)   # 25
print(e.age)          # 30

Output:

25
25
25
30

在 Python 中的一个函数上使用多个装饰器

def my_decorator(func):
    def wrapper():
        print("Step - 1")
        func()
        print("Step - 3")
    return wrapper


def repeat(func):
    def wrapper():
        func()
        func()
        func()
    return wrapper


@my_decorator
@repeat
def start_steps():
    print("Step - 2")


start_steps()

Output:

Step - 1
Step - 2
Step - 2
Step - 2
Step - 3

在 Python 中的方法中同时访问 cls 和 self

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhouluobo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值