寒假Python高级培训第二次

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

from types import MethodType#导入模块

class Cat(object):#定义一个类
    def eat(self):#定义一个方法
        print("吃")


cat1=Cat()#实例化对象

def run(self):#新定义一个类
    print("跑")

cat1.run =MethodType(run,cat1)#将类加入
cat1.run()

运算符重载

Python同样支持运算符重载,我们可以对类的专有方法进行重载,实例如下:

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b
 
   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)
 
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

运行结果

Vector(7,8)

pow和比较方法重写

import operator

class car(object):#定义一个类
    def __init__(self,num):#将成绩分别传给参数
        self.num=num

    def __pow__(self, power, modulo=None):#pow方法重写
        return pow(self.num,2)
G1=car(11)#实例化对象
G2=car(22)
G3=car(22)
G4=car(10)

print(operator.lt('G1','G4'))#比较方法重写

#operator.lt()函数是运营商模块的库函数,
# 它被用于在两个值并返回true执行“小于操作”
# 如果第一值小于所述第二值,假 ,否则。为真


print(pow(G1,2))#输出结果
print(pow(G2,2))
print(pow(G3,2))
print(pow(G4,2))

因为cmp在python3中被取消,所以比较使用的是operator.lt

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值