魔法方法&单例模式

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__())
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容