Python小推车python学习

Python学习打call第三十天:魔术方法

2019-03-02  本文已影响32人  暖A暖

1.什么是魔术方法

2.基本魔术方法

3.有关属性魔术方法

4.运算符相关魔术方法

class Student:
    def __init__(self, x):
        self.x = x

    def __add__(self, other):
        return self.x + other.x

    def __sub__(self, other):
        return self.x - other.x

a = Student(100)
b = Student(200)
print(b-a)
print(b+a)

5.比较操作符相关魔术方法

6.容器相关的魔术方法

class Student:
    def __init__(self):
        self.items = {}

    def __len__(self):
        return len(self.items)

    # 如果stu.items不为空,返回True
    def __bool__(self):
        return True if len(self) else False

    def __iter__(self):
        return iter(self.items)

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

    def __setitem__(self, key, value):
        self.items[key] = value

stu= Student()

stu.items['Course'] = 'Python'
stu.items['Teacher'] = '张三'
print(len(stu))

print(bool(stu))
print(iter(stu))
print(stu['Course'])

stu['Course'] = 'HTML'
print(stu['Course'])

7.可调用对象

# 函数是可调用对象
def add():
    pass

add.__call__()
add()

# 类实现了__call__方法
class Add():
    def __call__(self, *args, **kwargs):
        print(args)
        print(kwargs)

add_instance = Add()

add_instance.__call__(1,2,3, course='Python')

add_instance(1,2,3,course='Python')

参考:https://www.9xkd.com/user/plan-view.html?id=3623904578

上一篇 下一篇

猜你喜欢

热点阅读