面向对象
一、方法
"""
1)对象方法
怎么定义:直接定义在类中的函数
怎么调用:通过对象调用
特点:有默认参数self,self在调用的时候不用传参,系统自动将当前对象传给self
什么时候用:如果实现函数的功能需要对象属性就使用对象方法(对象方法中的self可以用来提供需要所有的对象属性)
2)类方法
怎么定义:在类中定义函数前加装饰器@classmethod
怎么调用:通过类调用
特点:自带参数cls,cls在调用的时候也不需要传参,系统会自动将当前类传给cls(谁调用就指向谁)
什么时候用:实现函数功能在不需要对象属性的时候需要类,就使用类方法。
3)静态方法
怎么定义:在类型定义函数前加装饰器@staticmethod
怎么调用:通过类调用
特点:没有默认参数
什么时候用:实现函数的功能既不需要类也不需要对象属性就使用静态方法
"""
class A:
num = 19
def func1(self):
print('对象方法', self)
print(A.num)
@classmethod
def func2(cls):
print('类方法', cls)
@classmethod
def func3(cls, x):
print(x, A.num)
@staticmethod
def func4():
print('静态方法')
print(A)
A.func2()
A.func3(100)
A.func4()
class Person:
def __init__(self, name):
print('init')
self.name = name
def eat(self, food):
print(f'{self.name}今天吃了{food}')
p = Person('k')
a = A()
a.func1()
A.func2()
print('=============')
a.func2()
A.func4()
a.func4()
class Math:
pi = 3.1415926
@staticmethod
def sum(num1, num2):
return num2 + num1
new_dict = dict.fromkeys('abcs')
print(new_dict)
二、对象属性的增删改查
class Person:
def __init__(self, name, tel, age=18, gender='男'):
self.name = name
self.age = age
self.tel = tel
self.gender = gender
def __repr__(self):
return f'<{str(self.__dict__)[1:-1]}>'
p1 = Person('小明', '110')
p2 = Person('小花', '120', 20, '女')
print(p1)
print(p2)
print(p1.name)
print(getattr(p1, 'name'))
value = 'name'
print(getattr(p1, value))
print(getattr(p1, 'height', 170))
print('修改前:', p1)
p1.age = 20
print('修改后:', p1)
p1.weight = 65
print('增加后:', p1)
setattr(p1, 'age', 30)
print(p1)
setattr(p1, 'height', 170)
print(p1)
del p1.gender
print(p1)
delattr(p1, 'weight')
print(p1)
stu1 = {'name': '小明', 'age': 23, 'tel': '110'}
stu2 = {'name': '小明', 'age': 18, 'tel': '120'}
class Student:
def __init__(self, name, tel, age=18):
self.name = name
self.age = name
self.tel = tel
stu11 = Student('小红', '120')
stu12 = Student('小明', '110', 12)
三、内置类属性
class Dog:
"""狗类"""
num = 20
def __init__(self, name, age=3, color='白色', gender='公'):
self.name = name
self.gender = gender
self.age = age
self.color = color
def show_message(self):
print(self.name, self.gender, self.age, self.color)
@classmethod
def show_num(cls):
print('狗的数量:', cls.num)
@staticmethod
def info():
print('狗是人类的朋友!')
dog = Dog('财财')
print(Dog.__doc__)
print(int.__doc__)
print(dog.__class__)
print(type(dog))
print(Dog.__name__)
data = [12, 12.34, 'abc', 'ancm', (10, 20), 23, 'name', True, True, False]
for x in data:
file_name = type(x).__name__
with open(f'./files/{file_name}.txt', 'a', encoding='utf-8') as f:
f.write(str(x)+',')
print(Dog.__module__, int.__module__, list.__module__)
print(Dog.__dict__)
print(dog.__dict__)
print(Dog.__bases__)
四、运算符的重载
from copy import copy
12 + 20
'abc'+'123'
class Student:
def __init__(self, name, age=18, score=0):
self.name = name
self.age = age
self.score = score
def __repr__(self):
return f'<{str(self.__dict__)[1:-1]}>'
def __lt__(self, other):
return self.score < other.score
def __add__(self, other):
return [self, other]
def __mul__(self, other):
return [copy(self) for _ in range(other)]
stu1 = Student('小明', score=90, age=40)
stu2 = Student('小红', age=20, score=80)
stu3 = Student('Tom', age=31, score=89)
print(stu1 != stu2)
print(stu1 + stu2)
print(stu1 + stu3)
result = stu1*3
print(result)
students = [stu1, stu2, stu3]
students.sort()
print(students)