面向对象【特殊方法】

面向对象特殊方法

class Foo(object):
    def __init__(self, a1, a2):
        self.a1 = a1
        self.a2 = a2

    def __call__(self, *args, **kwargs):
        print(11111, args, kwargs)
        return 123

    def __getitem__(self, item):
        print(item)
        return 8

    def __setitem__(self, key, value):
        print(key, value, 111111111)

    def __delitem__(self, key):
        print(key)

    def __add__(self, other):
        return self.a1 + other.a2

    def __enter__(self):
        print('1111')
        return 999

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('22222')

# 1. 类名() 自动执行 __init__
obj = Foo(1,2)

# 2. 对象() 自动执行 __call__
ret = obj(6,4,2,k1=456)

# 3. 对象['xx']  自动执行 __getitem__
ret = obj['yu']
print(ret)

# 4. 对象['xx'] = 11  自动执行 __setitem__
obj['k1'] = 123

# 5. del 对象[xx]     自动执行 __delitem__
del obj['uuu']

# 6. 对象+对象         自动执行 __add__
obj1 = Foo(1,2)
obj2 = Foo(88,99)
ret = obj2 + obj1
print(ret)

# 7. with 对象        自动执行 __enter__ / __exit__
obj = Foo(1,2)
with obj as f:
    print(f)
    print('内部代码')
#8.__new__ 构造方法
class Foo(object):
    def __init__(self, a1, a2):     # 初始化方法
        self.a1 = a1
        self.a2 = a2

    def __new__(cls, *args, **kwargs): # 构造方法
        return object.__new__(cls) # Python内部创建一个当前类的对象(初创时内部是空的.).

obj1 = Foo(1,2)
print(obj1)

obj2 = Foo(11,12)
print(obj2)
# 9.__str__ 打印对象时,默认输出该方法的返回值
class Foo(object):
    def __init__(self):
        pass

    def func(self):
        pass

    def __str__(self):
        return "F1"

obj = Foo()
print(obj, type(obj))
#10. __doc__ 表示类的描述信息
class Foo(object):
    """
    asdfasdfasdfasdf
    """
    def __init__(self):
        pass

    def func(self):
        pass

    def __str__(self):
        return "F1"

obj = Foo()
print(obj.__doc__)
#11. __dict__ 类或者对象的所有成员
class Foo(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def func(self):
        pass
obj1 = Foo('刘博文', 99)
obj2 = Foo('史雷', 89)

print(obj1.__dict__)  # {'name': '刘博文', 'age': 99}
print(obj2.__dict__)  # {'name': '史雷', 'age': 89}
#12. __iter__ 用于迭代器
# l1是list类的一个对象,可迭代对象
l1 = [11, 22, 33, 44]

# l2是list类的一个对象,可迭代对象
l2 = [1, 22, 3, 44]

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

    def func(self):
        pass

    def __iter__(self):
        # return iter([11,22,33,44,55,66])
        yield 11
        yield 22
        yield 33

obj1 = Foo('刘博文', 99)

for item in obj1:
    print(item)
原文地址:https://www.cnblogs.com/shanae/p/9555376.html