2022 Python寒假级高培训 第二次 笔记

动态给实例添加属性和方法

例子:

from types import MethodType  #用于动态添加方法,引入MethodType

class cat(object):
    pass                #定义一个空类
cat1 = cat()
cat1.name = "Tom"       #动态添加属性
print(cat1.name)

def run(self):          #先定义一方法
    print(self.name+"在奔跑")

cat.run = MethodType(run,cat1)  #动态添加方法

cat1.run()              #调用方法

限制动态添加属性__slots__

class cat(object): __slots__=("name","age") #限制实例属性,只能添加括号内有的属性

运算符的重载

 

例子:__add__

class Person(object):
    def __init__(self,num):
        self.num = num
    #运算符重载
    def __add__(self, other):
        return Person(self.num + other.num)
    def __str__(self):
        return "num = "+str(self.num)

per1 = Person(1)
per2 = Person(2)
print(per1+per2)

__lt__ :

# operator.lt(a, b)
import operator
# print(operator.lt(3, 2)) #前面的数小于后边的数 为Ture
# print(operator.lt(1, 2)) #前面的数大于后边的数 为False
class Grade(object):
    def __init__(self,num):
        self.num = num
    #lt运算符重载
    def __lt__(self, other):
        if self.num > other.num: #冒号一定不同要忘记
            return 1
        if self.num == other.num:
            return 0
        if self.num < other.num:
            return 2
    # def __str__(self):
    #     return "num = "+str(self.num)
# print(pow(2,2))
gra1 = Grade(2)
gra2 = Grade(3)
print(operator.lt(gra2, gra1))
# print(pow(gra1,2))

__pow__ #平方

class Grade(object):
    def __init__(self,num):
        self.num = num
    #lt运算符重载        平方
    def __pow__(self, power, modulo=None):
        return Grade(pow(self.num,power))
    def __str__(self):
        return "num = "+str(self.num)
# print(pow(2,2))
gra1 = Grade(2)     #定义一个对象
print(pow(gra1,2))  #验证运算符的重载


pow讲解:
https://blog.csdn.net/weixin_39712705/article/details/112315901

operator --- 标准运算符替代函数:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值