标签:实例化 *args highlight pre ict als pytho 实例 def
class Foo(object): def __init__(self, name, age): self.name = name self.age = age def __getitem__(self, item): if hasattr(self, item): return self.__dict__[item] def __setitem__(self, key, value): self.__dict__[key] = value def __delitem__(self, key): del self.__dict__[key] foo = Foo("adong", "28") print foo["name"], foo["age"] foo["height"] = "175" print foo["height"] del foo["height"] print foo["height"] >>> adong 28 175 None
class F: def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): return object.__new__(cls) f1 = F("adong") f2 = F("aqiang") print f1 print f2 >>> <__main__.F instance at 0x0000000003A70E88> <__main__.F instance at 0x0000000003A70E48> # 实例化的结果是两个对象
class F: __instance = False def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): if cls.__instance: return cls.__instance else: cls.__instance = object.__new__(cls) return cls.__instance f1 = F("adong") f2 = F("aqiang") print f1 print f2 >>> <__main__.F instance at 0x0000000003A90E88> <__main__.F instance at 0x0000000003A90EC8> # 单例模式,但是地址不一样,不知道是哪里的问题
标签:实例化 *args highlight pre ict als pytho 实例 def
原文地址:https://www.cnblogs.com/chenadong/p/9595565.html