内置方法 常用模块

__new__

在init 之前 , 实例化对象的第一步是__new__创建一个空间

class Foo:
    def __init__(self):                 # 初始化方法
        print('执行了init')
    def __new__(cls, *args, **kwargs):  # 构造方法
        # object.__new__(cls)
        print('执行了new')
        return object.__new__(cls)     #如果这个return不写,init方法永远不会执行

obj = Foo()

执行了new    先执行new
执行了init

创造一个对象  比喻成  捏小人

new 是小人捏出来

init 是小人穿衣服

设计模式  常用的23种

源头是从java里来得  因为Java 开发一个项目 很庞大,个方面人员需要配合,就相应出了一些标准,这样比较好对接。

python  :

  推崇设计模式 :会java 也会python  从java转的python

  贬低设计模式:纯python开发  因为python 一两个人就可以开发一个项目

单例模式:   一个类 只有一个实例  

class Foo:
    __instance = None
    def __init__(self,name,age):                 # 初始化方法
        self.name = name
        self.age = age
        self.lst = [name] 
        #self.lst = [age] 那就只打印年龄 上面的name 被覆盖
        # self。lst = [name,age] 打印名字和年龄
def __new__(cls, *args, **kwargs): # 构造方法 if cls.__instance is None: cls.__instance = object.__new__(cls) return cls.__instance obj1 = Foo('alex',20) obj2 = Foo('egon',22) print(obj1.lst,obj2.lst)       最后结果 print ['egon'] ['egon']

__del__

class Foo:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.file = open('file',mode = 'w')
    def write(self):
        self.file.write('sjahgkldhgl')
    def __del__(self):    # 析构方法 : 在删除这个类创建的对象的时候会先触发这个方法,再删除对象
        # 做一些清理工作,比如说关闭文件,关闭网络的链接,数据库的链接
        self.file.close()
        print('执行del了')

f = Foo('alex',20)                   # 只要写了这个__del__ 这个方法,他必定执行,所以可以写一个关闭文件放着,以防别人忘记关或者自己,写这个方法上个保险
print(f)                              这个方法就是垫底的 别的程序走完 然后走他 最后一道保险

__len__

 和len( )这个内置函数  其实差不多  int 和float  不适用  这个__len__同样不适用

# len()  lst dict set str

# print('__len__' in dir(list))
# print('__len__' in dir(dict))
# print('__len__' in dir(set))
# print('__len__' in dir(tuple))
# print('__len__' in dir(str))
#

# print('__len__' in dir(int))
# print('__len__' in dir(float))    #后面两个都是返回 False

__eq__

可以自定义   两个值是否相等

__hash__

class Foo():
    pass

obj1 = Foo()
obj2 = Foo()
print(hash(obj1)) 
print(hash(obj1))

两个对象的内存地址都不一样

猜你喜欢

转载自www.cnblogs.com/single82/p/9581807.html