Maison  >  Article  >  développement back-end  >  python函数重写怎么理解

python函数重写怎么理解

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼original
2019-06-25 15:43:333968parcourir

在自定义类内添加相应的方法,让自定义类创建的实例能像内建对象一样进行内建函数操作,这就是函数重写。

对象转字符串函数:repr(obj) ,返回一个能代表此对象的表达式字符串,通常eval(repr(obj)) == obj  (这个字符串通常是给python解释执行器运行用的),str(obj)  通过给定的对象返回一个字符串(这个字符串通常是给人阅读的)。

python函数重写怎么理解

对象转字符串函数的重写方法:

repr(obj) 函数的重写方法:

def __repr__(self):

str(obj) 函数的重写方法:

def __str__(self):

说明:

1. str(obj) 函数先查找, obj.__str__()方法,调用此方法并返回结果

2. 如果没有obj.__str__()方法时,则返回obj.__repr__()方法的结果并返回

3. 如果obj.__repr__方法不存在,则调用object类的__repr__实例方法显示8b988a0d974fd8aab2b69bf9b2cf8564格式的字符串

示例:

# 此示例示意通过重写 repr 和 str方法改变转为字符串的规则
class MyNumber:
    def __init__(self, value):
        '构造函数,初始化MyNumber对象'
        self.data = value
 
    def __str__(self):
        '''转换为普通人识别的字符串'''
        # print("__str__方法被调用!")
        return "自定义数字类型对象: %d" % self.data
 
    def __repr__(self):
        '''转换为eval能够识别的字符串'''
        return 'MyNumber(%d)' % self.data
 
 
n1 = MyNumber(100)
n2 = MyNumber(200)
print('repr(n1) ====>', repr(n1))
print('str(n2)  ====>', str(n2))

相关推荐:《Python视频教程

其它内建函数的重写方法:

  __abs__       abs(obj)  函数

  __len__       len(obj)  函数(必须返回整数)

  __reversed__  reversed(obj) 函数(必须返回可迭代对象

  __round__     round(obj)  函数

示例:

# 此示例示意abs 函数的重写
class MyInteger:
 
    def __init__(self, v):
        self.data = v
 
    def __repr__(self):
        return 'MyInteger(%d)' % self.data
 
    def __abs__(self):
        v = abs(self.data)
        return MyInteger(v)  # 用v创建另一个MyInteger对象
 
    def __len__(self):
        return 10000
 
I1 = MyInteger(-10)
print('I1 =', I1)
 
I2 = abs(I1)
print("I2 =", I2)
 
print('len(I2)=', len(I2))  # 10000

数值转换函数的重写:

  __complex__  complex(obj) 函数

  __int__      int(obj) 函数

  __float__    float(obj) 函数

  __bool__     bool(obj) 函数     (见下面布尔测试函数重载)

示例:

# 此示例示意数据转换构造函数的重写方法
class MyNumber:
 
    def __init__(self, value):
        self.data = value
 
    def __repr__(self):
        return 'MyNumber(%d)' % self.data
 
    def __int__(self):
        'int函数的重载'
        return self.data
 
n1 = MyNumber(100)
x = int(n1)
print(n1)
 
print(bool(n1))  # True
n2 = MyNumber(0)
print(bool(n2))  # True

布尔测试函数重写:

格式:

    __bool__

作用:

    用于bool(obj) 函数取值

    用于if语句的真值表达式中

    用于while 语句的真值表达式中

说明:

    1. 当自定义的类内有 __bool__(self) 方法时,以此方法的返回值作为bool(obj) 的返回值

    2. 当不存在__bool__(self) 方法时,bool(x) 返回__len__(self) 方法的返回值是否为零来测试布尔值

    3. 当不存在__len__(self) 方法时,则直接返回True

示例:

# 此示例示意bool(x) 函数的重写
class MyList:
    '自定义类型的列表,用来保存数据,内部用一个列表来存储数据'
 
    def __init__(self, iterable=()):
        self.data = [x for x in iterable]
 
    def __repr__(self):
        return 'MyList(%s)' % self.data
 
    def __len__(self):
        '''返回长度'''
        print("__len__方法被调用")
        return len(self.data)
 
    def __bool__(self):
        print("__bool__方法调用")
        for x in self.data:
            if not x:
                return False
        return True
        # return False  # <<=== 所有对象都为False
 
myl = MyList([0, -1, 2, -3])
# myl = MyList()
print(myl)
print(bool(myl))
if myl:
    print("myl为真值")
else:
    print(&#39;myl为假值&#39;)

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn