面向对象02
1.对象的增删改查
class Student:
def __init__(self, name, tel, stu_id='0001', score=0):
self.name = name
self.tel = tel
self.study_id = stu_id
self.score = score
# 在打印一个对象的时候, 系统会自欧东用这个对象去调用__repr__方法, 并且获取这个方法的返回值,
# 返回值是什么就打印什么, (返回值必须是字符串)
def __repr__(self):
return f'<{str(self.__dict__)[1:-1]}>'
stu1 = Student('小明', '13654124', score=80)
stu2 = Student('老王', '1202154', '0002', score=78)
print(stu1)
print(stu2)
1.查 - 获取对象的值
对象.属性
getattr(对象, 属性名)
print(stu1.name)
- getattr可以做到动态获取属性的值
value = input(“请输入需要获取的值”)
print(getattr(stu1, value)) - print(getattr(stu1,‘height’)) # 不存在会报错
print(getattr(stu1, ‘value’, 120)) # 给不存在的属性赋默认值不会报错 120
2.增/改
对象.属性 = 值
setattr(对象, 属性名, 值)
属性存在就是改
stu1.name = '小红' # <'name': '小红', 'tel': '13654124', 'study_id': '0001', 'score': 80>
print(setattr(stu1, 'tel', '120'))
print(stu1) # <'name': '小红', 'tel': '120', 'study_id': '0001', 'score': 80>
# 属性不存在就是增加
stu1.height = 178
print(stu1) # <'name': '小红', 'tel': '13654124', 'study_id': '0001', 'score': 80, 'height': 178>
3.删
del 对象.属性
delattr(对象, 属性名)
del stu1.study_id
print(stu1) # <'name': '小红', 'tel': '120', 'score': 80, 'height': 178>
delattr(stu1, 'score')
print(stu1) # <'name': '小红', 'tel': '120', 'height': 178>
2.类方法和静态方法
1.方法
1) 对象方法
怎么定义:
怎么调用: 对象.方法名()
特点: self
什么时候用: 如果实现函数的功能需要用到对象属性,那么这个函数就定义成对象方法
2) 类方法
怎么定义: 在定义函数前加装饰器 @classmethod
怎么调用: 类.方法名()
特点: 有一个默认参数(cls),这个参数在调用的时候不用传参, 系统会自动将当前类传给cls
什么时候用: 实现函数的功能不需要对象或者对象属性的前提下需要类就是用类方法
3) 静态方法
怎么定义: 在定义函数前加装饰器 @staticmethod
怎么调用: 类.方法名()
特点: 没有默认参数(相当于类中的普通函数)
什么时候用: 实现函数的功能在不需要对象属性的前提下不需要类就是用静态方法