day18-面向对象02

面向对象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)

  1. getattr可以做到动态获取属性的值
    value = input(“请输入需要获取的值”)
    print(getattr(stu1, value))
  2. 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
怎么调用:.方法名()
特点: 没有默认参数(相当于类中的普通函数)
什么时候用: 实现函数的功能在不需要对象属性的前提下不需要类就是用静态方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值