魔法方法&单例模式

new

触发: 类进行实例化时
功能: 控制对象的创建
参数: 至少一个cls(类本身)
返回: 使用cls创建的对象

new与init对比

1 new 触发比 init要早
    
2 new  是创建对象的
    init 初始化对象


new和init的参数问题:
    new 和 init 参数是同步的,
    接收的参数个数和类型都要相同
    可以使用 *args **kwargs

new的注意事项

new如果没有产生自身对象, 则类内置的所有方法将不会执行
    
类被调用的返回值由new产生

new基本用法

class Boat(object):
   def __new__(cls, *args, **kwargs):
      print(cls)

      # 通过object的new方法, 创建对象
      # 传入cls表示创建哪一个类的对象
      obj = object.__new__(cls)

单例模式

单例模式:
   只创建一个对象, 节省内存空间
   应用在对象只调用, 不添加成员的情况下
   
思想:
   当前类没有创建过对象, 就创建一个对象, 保存在类属性中
   当前类已经创建过对象, 就从类属性中寻找, 返回到类调用处

# 1. 基本写法
class Sington(object):
   # 保存单例对象的类属性
   __instance = None
   
   def __new__(cls, *args, **kwargs):
      
      # 如果没有创建过对象的情况, 就创建对象保存在类属性中
      if not cls.__instance:
         cls.__instance = object.__new__(cls)
         
      # 如果创建过类对象了, 就返回类属性
      return cls.__instance

析构方法 __ del__

class LangGou(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    def __del__(self):
        print('析构方法被触发')
        return 1
        

# 创建一个对象
lang = LangGou('汪汪')

# 删除对象的引用
del globals()['lang']
# 在单例模式下, 要把类的私有属性也要删除
# 没有引用指向对象才会触发析构方法
del LangGou._LangGou__instance

call

触发: 调用对象时触发
功能: 对象名当做函数名, call方法体当做函数体
参数: self....
返回: 随意

# 1.基本用法
class MyClass(object):
   def __call__(self):
      print(123)
      return 456


obj = MyClass()
obj()

str和repr

触发: print(obj), str(obj)
功能: 查看对象
参数: self...
返回: str


触发: repr(obj)
功能: 查看对象
参数: self
返回: str

# __str__ = __repr__
# 没有实现str方法时, 才会去使用repr
# 只有repr(obj)时, 才会调用repr

repr,str使用

class MyClass1(object):
   def __str__(self):
      return 'MyClass1的str方法'


class MyClass2(object):
   def __repr__(self):
      return 'MyClass2的repr方法'


class MyClass3(object):
   def __str__(self):
      return 'MyClass3的str方法'

   def __repr__(self):
      return 'MyClass3的repr方法'


class MyClass4(object):
   pass

print('=================')
print('obj', obj1)
print('str', str(obj1))
print('repr', repr(obj1))
print('=================')
print('obj', obj2)
print('str', str(obj2))
print('repr', repr(obj2))
print('=================')
print('obj', obj3)
print('str', str(obj3))
print('repr', repr(obj3))
print('=================')
print('obj', obj4)
print('str', str(obj4))
print('repr', repr(obj4))
print('=================')


# 运行结果:
=================
obj MyClass1的str方法
str MyClass1的str方法
repr <__main__.MyClass1 object at 0x000002BDB7FE9550>
=================
obj MyClass2的repr方法
str MyClass2的repr方法
repr MyClass2的repr方法
=================
obj MyClass3的str方法
str MyClass3的str方法
repr MyClass3的repr方法
=================
obj <__main__.MyClass4 object at 0x000002BDB7FE9208>
str <__main__.MyClass4 object at 0x000002BDB7FE9208>
repr <__main__.MyClass4 object at 0x000002BDB7FE9208>
=================

Number系列

触发: bool(obj), int(obj), float(obj), complex(obj)
功能: 强转对象
参数: self
返回: bool, int, float, complex


class MyClass(object):
    def __bool__(self):
        return False

    def __int__(self):
        return 123

    def __float__(self):
        return 3.14

    def __complex__(self):
        return 1+1j

obj = MyClass()
print(bool(obj))
print(int(obj))
print(float(obj))
print(complex(obj))


# 运行结果:
False
123
3.14
(1+1j)

add和radd

触发: 使用对象进行加法运算
功能: 加法运算
参数: 两个对象参数
返回: 运算后的值

obj在加号左侧会触发add(), 
并且把右侧的数字传入到add内的other参数内
radd正好相反


class MyClass(object):
    def __add__(self, other):
        return 1 + other

    def __radd__(self, other):
        return 10 + other


obj = MyClass()
obj2 = MyClass()





# other接收2数字对象, 返回3 (1+2)
res = obj + 2
print(res)


# 首先触发add(),
# 1 + other, 返回值为: 1+obj2
# 再触发radd()
# 10 + other, 返回值: 10 + 1
res = obj + obj2
print(res)

len

触发: len(obj)
功能: 检测指定内容的个数
参数: self..
返回: int


# len(obj) 返回内部自定义成员个数
class MyClass(object):
    a = 1
    b = 2
    
    def func1(self):
        pass
        
    def func2(self):
        pass


    def __len__(self):
        # 通过MyClass.__dict__, 取出所有MyClass的所有类属性
        # 把非双下划线的属性加入list, 返回list长度
        li = [i for i in MyClass.__dict__ if not (i.startswith('__') and i.endswith('__'))]

        return len(li)


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

推荐阅读更多精彩内容