python--__repr__、__del__、__eq__

__repr__

__str__ : str(obj),要求必须实现了__str__,要求这个方法的返回值必须是字符串str类型

__repr__: 是__str__的备胎.如果有__str__方法,那么print %s str都先去执行__str__方法,并且使用__str__的返回值 如果没有__str__,那么 print %s str都会执行repr方法


在子类中使用__str__,先找子类的__str__,没有的话要向上找,只要父类不是object,就执行父类的__str__,但是如果除了object之外的父类都没有__str__方法,就执行子类的__repr__方法,如果子类也没有,还要向上继续找父类中的__repr__方法.一直找不到 再执行object类中的__str__方法

print('---%r---' % ('abc'))
print('---%s---' % ('abc'))

结果:

---'abc'---
---abc---

class A:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return '**%s**' % self.name

    def __repr__(self):
        return self.name


class B(A):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '***'


a = B('zou')
print(a)
print(str(a), repr(a))
print('%s | %r' % (a, a))

结果:

**zou**
**zou** ***
**zou** | ***

__del__

__del__析构函数:在实例释放、销毁的时候自动执行的,通常用于做一些收尾工作。

构造方法 申请一个空间

析构方法 释放一个空间之前执行

class Dome:
    n = 123

    def __init__(self, name):
        self.name = name

    def __del__(self):  # 析构函数,不需要参数,放哪都可以
        print('析构函数测试')

    def talk(self):
        print('%s:say hello' % self.name)

    def sleep(self):
        print('we are sleep')


f1 = Dome('zou')
f1.talk()
f2 = Dome('jack')
f2.sleep()

结果:

zou:say hello
we are sleep
析构函数测试
析构函数测试

不需要调用,实例执行完会自动执行,上面有两个实例f1和f2,所以最后会执行两次

__eq__

class A:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if self.name == other.name and self.age == other.age:
            return True


a = A('zou', 83)
aa = A('zou', 83)
aa2 = A('zou', 83)

print(a, aa)
print(a == aa)  # ==这个语法 是完全和__eq__

结果:

<__main__.A object at 0x0323B210> <__main__.A object at 0x0323B270>
True

class Employee:
    def __init__(self, name, age, sex, partment):
        self.name = name
        self.age = age
        self.sex = sex
        self.partment = partment

    def __hash__(self):
        return hash('%s%s' % (self.name, self.sex))

    def __eq__(self, other):
        if self.name == other.name and self.sex == other.sex:
            return True


employ_lst = []
for i in range(200):
    employ_lst.append(Employee('a', i, 'male', 'python'))
for i in range(200):
    employ_lst.append(Employee('b', i, 'male', 'python'))
for i in range(200):
    employ_lst.append(Employee('c', i, 'male', 'python'))

# print(employ_lst)
employ_set = set(employ_lst)
for person in employ_set:
    print(person.__dict__)

结果:

{'name': 'b', 'age': 0, 'sex': 'male', 'partment': 'python'}
{'name': 'c', 'age': 0, 'sex': 'male', 'partment': 'python'}
{'name': 'a', 'age': 0, 'sex': 'male', 'partment': 'python'}

set集合的去重机制 : 先调用hash,再调用eq,eq不是每次都触发,只有hash值相等的时候才会触发

原文地址:https://www.cnblogs.com/zouzou-busy/p/13022013.html