python内置方法

__str__ 方法 和__repr__方法

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

    def __str__(self):
        return "这个人的名字是%s, 这个人年龄是%d " % (self.name, self.age)

     def __repr__(self):
        print("调用repr函数")
        return "这个人的名字是%s, 这个人年龄是%d " % (self.name, self.age)

p = Person("zhangsan", 20)

#调用_str__方法
print(p)
print(type(p))

#调用str函数
s = str(p)
print(s)
print(type(s))

#运行结果
这个人的名字是zhangsan, 这个人年龄是20 
<class '__main__.Person'>
这个人的名字是zhangsan, 这个人年龄是20 
<class 'str'>
调用repr函数
这个人的名字是zhangsan, 这个人年龄是20 

__call__ 方法:
作用:使得“对象”具备当做函数,来调用的能力
实现实例方法 __call__ 那么创建好的实例, 就可以通过函数的形式来调用

class penFactory:
    def __init__(self, p_type):
        self.p_type = p_type

    def __call__(self, *args, **kwargs):
        print("笔的类型是%s, 笔的颜色是%s" % (self.p_type, *args))

penG = penFactory("钢笔")
penG("红色")
penG("蓝色")

penQ = penFactory("铅笔")
penQ("黑色")
penQ("红色")

#运行结果
笔的类型是钢笔, 笔的颜色是红色
笔的类型是钢笔, 笔的颜色是蓝色
笔的类型是铅笔, 笔的颜色是黑色
笔的类型是铅笔, 笔的颜色是红色

对一个实例对象进行索引操作

class person:
    def __init__(self):
        self.cache = {}

    def __setitem__(self, key, value):
        # print(key, value)
        self.cache[key] = value

    def __getitem__(self, item):
        # print("item: ", item)
        return self.cache[item]

    def __delitem__(self, key):
        # print(key)
        del self.cache[key]

p = person()
p["name"] = "张三"
print(p["name"])
del p["name"]
print(p.cache)

#运行结果
张三
{}

对一个实例对象进行切片操作

class person:
    def __init__(self):
        self.it = [1, 2, 3, 4, 5, 6, 7, 8]

    def __setitem__(self, key, value):
        # print(key, value)
        self.it[key] = value

        def __getitem__(self, item):
        return self.it[item]

    def __delitem__(self, key):
        del self.it[key]


p = person()
p[1:4:2] = ["a", "b"]
print(p[0:7:2])
print(p[::])

del p[::]
print(p.it)

#运行结果
[1, 3, 5, 7]
[1, 'a', 3, 'b', 5, 6, 7, 8]
[]

对一个实力对象的比较操作

class Person:
    def __init__(self, age, height):
        self.age = age
        self.height = height

    # 相等 (==)
    def __eq__(self, other):
        print("__eq__")
        return self.age == other.age

    # 不相等(!=)
    def __ne__(self, other):
        pass

    # 小于(<)
    def __lt__(self, other):
        print("__lt__")
        return self.age < other.age

    # 小于或等于(<=)
    def __le__(self, other):
        pass

    # 大于(>)
    def __gt__(self, other):
        print("__gt__")
        return self.age > other.age

    # 大于或等于(>=)
    def __ge__(self, other):
        pass

p1 = Person(18, 170)
p2 = Person(17, 180)
print(p1 > p2)
print(p1 == p2)

#运行结果
__gt__
True
__eq__
False

使用装饰器装饰类 @functools.total_ordering , 自动生成"反向" "组合"的方法

import functools

@functools.total_ordering
class Person:
    def __init__(self, age, height):
        self.age = age
        self.height = height
    # ==
    def __eq__(self, other):
        print("__eq__")
        return self.age == other.age
    # >
    def __gt__(self, other):
        print("__gt__")
        return self.age > other.age

p1 = Person(18, 170)
p2 = Person(17, 180)
# print(p1 <= p2)

print(Person.__dict__)
print(p1 <= p2)

实现__bool__ 方法,设置对象在上下问环境中的布尔值

class Person:
    def __init__(self, age):
        self.age = age

    def __bool__(self):
        if self.age > 18:
            return True
        else:
            return  False

p = Person(17)

if p:
    print("可以上网了")

让我们自己创建的对象可以使用for in 进行遍历,有两种方法:
第一种方法,实现实现 __getitem__ 方法, 优先级低,每次for in 获取数据时, 都会调用这个方法

class Person:
    def __init__(self, count):
        self.count = count

    def __getitem__(self, item):
        self.count += 1
        if self.count >= 6:
            raise StopIteration("停止遍历")
        return self.count

p = Person(1)
for i in p:
    print(i)

# 运行结果
2
3
4
5

第二中方法,实现 __iter__ 方法,优先级高,这个方法, 必须返回一个"迭代器"; 即, 具备 __iter____next__方法
当for in 遍历这个对象时, 会调用这个iter方法返回的迭代器对象的next方法

class Person:
    def __init__(self, count):
        self.count = count

    def __getitem__(self, item):
        self.count += 1
        if self.count >= 6:
            raise StopIteration("停止遍历")
        return self.count

    def __iter__(self):
        return iter([1, 2, 3, 4, 5 , 6])

p = Person(1)
for i in p:
    print(i)

#运行结果
1
2
3
4
5
6

class Person:
    def __init__(self, count):
        self.count = count

    # def __getitem__(self, item):
    #     self.count += 1
    #     if self.count >= 6:
    #         raise StopIteration("停止遍历")
    #     return self.count

    def __iter__(self):
        return self
        # return iter([1, 2, 3, 4, 5 , 6])

    def __next__(self):
        self.count += 1
        if self.count >= 6:
            raise StopIteration("停止遍历")
        return self.count


p = Person(1)
for i in p:
    print(i)

#运行结果
2
3
4
5

可迭代对象只要实现__iter__ 方法,迭代器必须要实现 __iter__ 方法和 __next__方法;
__iter__ 方法可以恢复迭代器的初始化值, 复用迭代器

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容