Home  >  Article  >  Backend Development  >  How to understand python function rewriting

How to understand python function rewriting

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-25 15:43:333904browse

Add corresponding methods in the custom class so that the instances created by the custom class can perform built-in function operations like built-in objects. This is function rewriting.

Object to string function: repr(obj), returns an expression string that can represent this object, usually eval(repr(obj)) == obj (this string is usually interpreted and executed by python used to run the programmer), str(obj) returns a string through the given object (this string is usually read by humans).

How to understand python function rewriting

Rewriting method of object to string function:

Rewriting method of repr(obj) function:

def __repr__(self):

str(obj) function rewriting method:

def __str__(self):

Instructions:

1. The str(obj) function first searches, obj. __str__() method, call this method and return the result

2. If there is no obj.__str__() method, return the result of the obj.__repr__() method and return

3. If The obj.__repr__ method does not exist, then calling the __repr__ instance method of the object class displays a string in the format of 8b988a0d974fd8aab2b69bf9b2cf8564

Example:

# 此示例示意通过重写 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))

Related recommendations: "Python Video Tutorial"

How to rewrite other built-in functions:

__abs__ abs(obj) function

__len__ len(obj) function (must return an integer)

__reversed__ reversed(obj) function (must return an iterable object

__round__ round(obj) function

Example:

# 此示例示意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

Rewriting of numerical conversion function:

__complex__ complex(obj) function

__int__ int(obj) function

__float__ float(obj) function

__bool__ bool(obj) function (see Boolean test function overloading below)

Example:

# 此示例示意数据转换构造函数的重写方法
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

Boolean test function rewrite:

Format:

__bool__

Function:

Used for bool(obj) function value

Used in the truth value expression of if statement

Used for the truth value of while statement

description in the expression:

1. When there is a __bool__(self) method in the custom class, the return value of this method is used as bool(obj ) return value

2. When there is no __bool__(self) method, bool(x) returns whether the return value of the __len__(self) method is zero to test the Boolean value

3. When there is no __len__(self) method, True will be returned directly

Example:

# 此示例示意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('myl为假值')

The above is the detailed content of How to understand python function rewriting. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn