python学习第八章--python类的特殊方法

常见的特殊方法

  • 重写_repr_方法:用户自定义实现对象的“自我描述”的功能
    class Apple:
        def __init__(self, color, weight):
            self.color = color;
            self.weight = weight;
        # 重写_repr_()方法,用于实现Apple对象的“自我描述”
        def __repr__(self):
            return "Apple[color=" + self.color +\
                ", weight=" + str(self.weight) + "]"
    a = Apple("红色" , 5.68)
    print(a)
    
    Apple[color=红色, weight=5.68]

  • 析构方法_del_:用于销毁python对象(_init_()方法用于初始化对象)

        注:只有当对象的引用计数变成0时,该对象才会被回收

class Item:
    def __init__ (self, name, price):
        self.name = name
        self.price = price
    # 定义析构函数
    def __del__ (self):
        print('del删除对象')
# 创建一个Item对象,将之赋给im变量
im = Item('鼠标', 29.8)
# 打印im所引用的Item对象
del im
print('--------------')

  •  _dict_属性:可查看对象的所有内部状态,也可通过字典语法来访问或修改指定属性的值
class Item:
    def __init__ (self, name, price):
        self.name = name
        self.price = price
im = Item('鼠标', 28.9)
print(im.__dict__)  # ①
# 通过__dict__访问name属性
print(im.__dict__['name'])
# 通过__dict__访问price属性
print(im.__dict__['price'])
im.__dict__['name'] = '键盘'
im.__dict__['price'] = 32.8
print(im.name) # 键盘
print(im.price) # 32.8
{'name': '鼠标', 'price': 28.9}
鼠标
28.9
键盘
32.8
  • _getattr_ (self,name):当程序访问对象 name 属性且该属性不存在时被自动调用
  • _getattribute(self,name):当程序访问对象 name 属性时被自动调用
  • _setattr_(self,name,value):当程序对对象的name属性赋值时被自动调用
  • _delattr_(self,name):当程序删除对象的name属性时被自动调用

2.与反射相关的属性和方法

  • hasattr(obj , name):检查 obj 对象是否包含名为 name 的属性或方法
  • getattr(object, name[, default]): 获取 object 对象中名为 name 属性的属性值
  • setattr( obj, name, value ,/):将 obj 对象的 name 属性设为 value
class Comment:
    def __init__ (self, detail, view_times):
        self.detail = detail
        self.view_times = view_times
    def info ():
        print("一条简单的评论,内容是%s" % self.detail)

c = Comment('gigi', 20)
# 判断是否包含指定的属性或方法
print(hasattr(c, 'detail'))
print(hasattr(c, 'view_times'))
print(hasattr(c, 'info'))
# 获取指定属性的属性值
print(getattr(c, 'detail'))
print(getattr(c, 'view_times'))
# 由于info是方法,故下面代码会提示:name 'info' is not defined
#print(getattr(c, info, '默认值'))
# 为指定属性设置属性值
setattr(c, 'detail', '天气不错')
setattr(c, 'view_times', 32)
# 输出重新设置后的属性值
print(c.detail)
print(c.view_times)

# 设置不存在的属性,即为对象添加属性
setattr(c, 'test', '新增的测试属性')
print(c.test) # 新增的测试属性
True
True
True
gigi
20
天气不错
32
新增的测试属性
  • _call_属性:可通过判断该属性(或方法)是否包含 call 属性来确定它是 否可调用
    class User:
        def __init__(self, name, passwd):
            self.name = name
            self.passwd = passwd
        def validLogin (self):
            print('验证%s的登录' % self.name)
    u = User('crazyit', 'leegang')
    # 判断u.name是否包含__call__方法,即判断是否可调用
    print(hasattr(u.name, '__call__')) # False
    # 判断u.passwd是否包含__call__方法,即判断是否可调用
    print(hasattr(u.passwd, '__call__')) # False
    # 判断u.validLogin是否包含__call__方法,即判断是否可调用
    print(hasattr(u.validLogin, '__call__')) # True
    False
    False
    True
    

    3.与序列相关的特殊方法

  • _len_(self) :返回该序列包含的元素个数,
  • _getitem_ (self, key):该方法获取指定索引对应的元素。该方法的 key 应该是整数值或slice 对象,否则该方法会引发 KeyError 异常
  • _contains_(self,item): 该方法判断序列是否包含指定元素
  • _setitem_(self, key, value): 该方法设置指定索引对应的元素, 该方法的 key 应该是整数 值或 slice 对象,否则该方法会 KeyError 异常
  • _delitem_(self, key):该方法删除指定索引对应的元素
  • _iter_(self):返回一个迭代器(iterator),迭代器必须包含 _next_ () 方法, 该方法返回迭代器的下一个元素。
  • _reversed_(self):为内建的reversed()反转函数提供支持,当程序调用reversed()函数对指定迭代器执行反转时,实际上是由该方法实现的

4.创建生成器

  • 操作:1.定义一个包含yield语句的函数

                   2.调用第一步创建的函数得到生成器

def test(val, step):
    print("--------函数开始执行------")
    cur = 0
    # 遍历0~val
    for i in range(val):
        cur += i * step #在cur的基础上加i*step
        yield cur
# 执行函数,返回生成器
t = test(10, 2)
print('=================')
#获取生成器第一个值
print(next(t)) # 生成器冻结在yield处
print(next(t)) # 生成器再冻结在yield处
=================
--------函数开始执行------
0
2

yield cur语句的两个特点:a.每次返回一个值,类似return。b.冻结执行,程序每执行到yield就会被暂停,next()函数可获取生成器的下个值,程序才会继续。

注:python中,生成器创建的两种方式:a.使用for循环的生成器推导式

                                                                  b.调用yield语句的生成器函数

5.运算符重载的特殊方法

运算运算符
object._add_(self, other) 加法+
object. sub_(self, other)减法-
object. mul_(self, other)乘法*
object. _matmul_(self,other)矩阵乘法@
object. _truediv_(self ,other)除法/
object. _floordiv_(self ,other)整除//
object. _mod_(self ,other)求余%
object. _divmod_(self, other)求余运算divmod
object. _pow_(self ,other[,modulo])乘方**
object. _lshift_(self, other)左移<<
object. _rshift_(self, other)右移>>
object. _and_(self, other)按位与&
object. _xor_(self, other)按位异或^
object. _or_(self, other)按位或|

当程序执行 + 运算时,python 首先会尝试使用x的_ add_方法进行计算, 如果x没有提供add 方法, python 还会尝试调用y的_radd_方法进行 算。这意味着上面介绍的各种数值运算相关方法,还有一个带r的版本。(如object._radd_(self, other))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值