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