210224课堂整理
面向对象的方法
1,方法
1)对象方法(常用)
定义:直接定义在类中的函数
调用:通过对象来调用 调用:通过对象来调用
特点:有默认参数self,self在调用时不用传参
应用:如果实现函数的功能需要对象属性就使用对象方法
self可以用来提供需要所有的对象属性
2)类方法
定义:在类中定义函数前加装饰器 @classmethod
调用: 通过类调用
特点:自带参数cls,cls在调用时不需要传参
应用:实现函数功能在不需要对象属性的时候需要类,就使用类方法
3)静态方法
定义:在类中定义函数前加装饰器 @staticmethod
调用:通过类调用
特点:没有默认参数
应用:实现函数的功能既不需要类也不需要对象属性就使用静态方法
4)魔法方法
调用:自动调用
特点: _ _ init _ _
class A:
# func1是对象方法
def func1(self):
print('对象方法')
# func2和func3都是类方法
@classmethod
def func2(cls):
print('类方法', cls)
@classmethod
def func3(cls, x):
print('类方法')
# func4是静态方法
@staticmethod
def func4(x):
print('静态方法')
print(A)
A.func2()
A.func3(100)
A.func4()
2,方法在定义时的参数问题
确定参数的方法:
看实现函数的功能除了类中属性以外是否需要额外的数据
class Person:
def __init__(self, name):
print('init')
self.name = name
def eat(self, food):
print(f'{self.name}今天吃了{food}')
p = Person('k')
3,方法的调用问题
Python中不管什么方法都可以用对象和类调用
# 类可以调用对象方法
a = A()
a.func1()
# A.func1() 此方法无意义,会使self需要传参从而失去意义
# 对象可以调用类方法
A.func2()
a.func2() # 此方法会额外消耗cpu
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
# __repr__会在当前类的对象被打印的时候自动调用
# 并且打印结果就是这个函数的返回值,返回值是字符串
def __repr__(self):
# return str(self.__dict__)
return f'<{str(self.__dict__)[1:-1]}>'
p1 = Person('小明', '110')
p2 = Person('小花', '120', 20, '女')
print(p1) # print(p1) == print(p1.__repr__())
print(p2) # <'name': '小花', 'age': 20, 'tel': '120', 'gender': '女'>
1,查 获取对象属性的值
1) 对象.属性
2) getattr(对象,属性名)
getattr(对象,属性名,默认值)
print(p1.name)
print(getattr(p1, 'name'))
value = 'name'
# print(p1.value) # 报错!
print(getattr(p1, value))
# print(p1.height) # AttributeError: 'Person' object has no attribute 'height'
print(getattr(p1, 'height', 170)) # 170
2,增和改
1)对象.属性=值
2)setattr(对象,属性名,值)
print('修改前:', p1)
p1.age = 20
print('修改后:', p1)
p1.weight = 65
print('增加后:', p1)
setattr(p1, 'age', 30)
print(p1)
setattr(p1, 'height', 170)
print(p1)
3,删
1) del对象.属性 删除对象里面的全部属性
2) delattr(对象,属性名) 删除对象里的指定属性
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('财财')
1, _ _ doc _ _ 获取类的说明文档
print(Dog.__doc__)
print(int.__doc__)
2, _ _ class _ _ 获取对象的类型(对象属性),功能和type函数一样
print(dog.__class__)
print(type(dog))
3, _ _ name _ _ 获取类名(类属性)
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)+',')
4, _ _ module _ _ 获取类所在的模块的模块名
print(Dog.__module__, int.__module__)
5, _ _ dict _ _
1)将类转换为字典,获取指定类所有的类属性及其对应的值
2)将对象转换为字典,获取指定对象所有的对象属性及其对应的值
print(Dog.__dict__)
print(dog.__dict__)
6, _ _ base _ _ 获取指定类的父类
_ _ bases _ _ 获取指定类的父类们
object 是所有类的初代祖先
print(Dog.__bases__) # (<class 'object'>,)
运算符重载
1,Python中每一个运算符都对应一个固定的魔法方法,
每次在使用运算符的时候本质是调用对应魔法方法
调用类按运算符前面的来判定
数据是否支持某种运算符,和这个类型中有无对应的魔法方法有关
from copy import copy
12 + 20 # 12.__add__(20)
'abc'+'123' # 'abc'.__add__('123')
2,在自己的类中重载指定运算符
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
# self是+前面的数据,other是+后面的数据; 返回值是计算结果
def __add__(self, other):
# return self.score + other.score
return [self, other]
def __mul__(self, other):
return [copy(self) for _ in range(other)]
stu1 = Student('小明', score=90)
stu2 = Student('小红', age=20, score=80)
stu3 = Student('Tom', age=31, score=89)
print(stu1 != stu2) # 默认支持比较相等于
print(stu1 + stu2) # 相当于: print(stu1.__add__(stu2))
print(stu1 + stu3)
result = stu1*3 # stu1.__mul__(3)
print(result)
# del stu1.name
# print(result)
# 按年龄排序
students = [stu1, stu2, stu3]
students.sort()
print(students)