一些内置的魔术方法

1.__call__

# callable(对象):即判断对象()能不能运行

class A(object):
    def __call__(self, *args, **kwargs):
        print('----')


obj = A()
print(callable(obj))
obj()  # 调用这个类中的__call__方法

2.__len__

class Class(object):
    def __init__(self, name):
        self.name = name
        self.students = []

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


py22 = Class('py22')
py22.students.append('alex')
py22.students.append('lgq')

print(len(py22))


# 基本原理:
class B(object):
    def __init__(self, num):
        self.num = num

    def __my_magic__(self):
        return self.num ** 2


def my_magic(obj):
    return obj.__my_magic__()


b = B(10)
ret = my_magic(b)
print(ret)

3.__new__

实例化的时候:先创建一块对象的空间,通过类指针指向--> __new__
    即先调用__new__方法构造对象空间,再调用__init__接收对象空间即让self指向对象空间,

class A(object):
    def __new__(cls, *args, **kwargs): # 构造方法
        o = super().__new__(cls)
        print('执行new', o)
        return o

    def __init__(self):
        print('执行init', self)


a = A()

设计模式:单例模式

  一个类从头到尾只会创建一次self的空间,即多个对象共用一个空间地址

class Baby(object):
     __instanse = None

     def __new__(cls, *args, **kwargs):
         if cls.__instanse is None:
             obj = super().__new__(cls)
             cls.__instanse = obj

         return cls.__instanse

     def __init__(self, cloth, pants):
         self.cloth = cloth
         self.pants = pants


# b1 = Baby('红毛衣', '绿皮裤')
# b2 = Baby('白衬衫', '黑皮裤')
#
# print(b1.cloth)
# print(b2.cloth)


# 可以通过模块导入的方式实现单例模式
from 单例模式 import b1
print(b1)
print(b1)
print(b1)

4.__str__和__repr__

class Course(object):
    def __init__(self, name, price, period):
        self.name = name
        self.price = price
        self.period = period

    def __str__(self):
        return ','.join([self.name, str(self.price), str(self.period)])


py22 = Course('python', 21800, '6 months')
linux = Course('linux', 19800, '5 months')
mysql = Course('mysql', 12800, '3 months')

lst = [py22, linux, mysql]
# 打印一个对象时默认输出内存地址,如果希望输出想要的内容,需要在类中实现__str__方法返回内容
for index, c in enumerate(lst, 1):
    print(index, c)


class Class(object):
    def __init__(self):
        self.students = []

    def append(self, name):
        self.students.append(name)

    def __repr__(self):
        return str(self.students)

    def __str__(self):
        return 'LGQ'


"""
当我们打印一个对象 或者 用%s进行格式化输出 或者 str(对象) 总是调用该对象的__str__方法
如果找不到__str__,就调用__repr__方法

__repr__不仅是__str__的替代品,还有自己的功能
用%r进行格式化输出 或者 repr(对象)的时候总是调用这个对象的__repr__方法
"""
py = Class()
py.append('alex')

print(py)
print(str(py))
print('201703班级:%s' % py)

print('201703班级:%r' % py)
print(repr(py))

5.__eq__

# class Foo(object):
#     def __init__(self, num):
#         self.num = num
#
#
# v3 = [Foo(i) for i in range(10)]
#
# print(v3)
# for i in v3:
#     print(i.num)


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

    def __eq__(self, other): # 两个对象作比较时,自动调用这个方法
        # print('开始执行我了')
        # print(self)
        # print(other)
        # print('执行我结束了')
        if self.name == other.name and self.age == other.age:
            return True
        else:
            return False


alex = Person('alex', 32)
alex22 = Person('alex', 32)

print('-' * 20)
print(alex == alex22)
    # == 符号会调用两个对象对应类的__eq__方法,而第一个对象作为该方法的self参数,
    # 第二个对象作为该方法的other参数
    # 其打印结果为__eq__方法的返回值,所以我们可以自定义返回结果
print('-' * 20)

 

posted @ 2020-08-21 15:20  LGQ天  阅读(88)  评论(0编辑  收藏  举报