Python - 面向对象操作的简单梳理

该文章展示了Python中的类定义,包括初始化方法`__init__`,私有属性`__score`,以及`@classmethod`、`@staticmethod`、`@property`和`@setter`的使用。还涉及到了运算符重载(`__add__`)和MRO(MethodResolutionOrder)的概念。此外,文章演示了如何创建子类`LXH`并继承父类`Student`的属性和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Student:
    id = 0

    def __init__(self, name, score):
        self.name = name
        self.__score = score
        Student.id += 1

    def inf(self):
        print("ID: {}, Name: {}, Score: {}".format(Student.id, self.name, self.__score))

    @classmethod   # 类函数只能处理类属性,这里的类属性是id,在外面可以直接调用雷内属性
    def printName(cls):
        print(cls.id)

    @staticmethod  # 在类里写和类没多少关系的普通的方法
    def add(a, b):
        return a + b

    def __call__(self, *args, **kwargs):
        print("This is the call function")

    @property  # 相当于getter方法
    def get_score(self):
        return self.__score

    @get_score.setter  # 相当于setter方法
    def set_score(self, score):
        self.__score = score
        return self.__score

    # 运算符重载
    def __add__(self, other):
        if isinstance(other, Student):
            return other.__score + self.__score
        else:
            return "不是同类对象不能重载"


class LXH(Student): # 继承
    def __init__(self, name, score):
        Student.__init__(self, name, score)
        print(Student.id, name, score)


s1 = Student("lxh", 320)
s1.inf()
Student.printName()
print(Student.add(10, 20))
s1()  # 类对像可以直接调用call方法
print(s1.get_score)  # property可以让函数像属性一样被调用
s1.set_score = 350   # @get_score.setter可以像设置属性一样完成对函数的调用
print(s1.get_score)

l = LXH("lxh", 360)
l.set_score = 340  # getter/setter也可以被继承
print(l.get_score)
print(LXH.mro())  # 查看继承关系

s2 = Student("bjj", 320)
s2.inf()
print(s1 + s2)  # 在函数中选定对象的某个属性进行运算

print(s1.__dict__)
print(s1.__class__)
print(LXH.mro())
print(Student.__subclasses__())

ID: 1, Name: lxh, Score: 320
1
30
This is the call function
320
350
2 lxh 360
340
[<class ‘main.LXH’>, <class ‘main.Student’>, <class ‘object’>]
ID: 3, Name: bjj, Score: 320
670
{‘name’: ‘lxh’, ‘_Student__score’: 350}
<class ‘main.Student’>
[<class ‘main.LXH’>, <class ‘main.Student’>, <class ‘object’>]
[<class ‘main.LXH’>]

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值