zoukankan      html  css  js  c++  java
  • 类的常用方法

    _init_

    初始化,类名加括号自动执行

    class Foo:
        def __init__(self, name):
            self.name = name
    
    a = Foo("summer")
    

    _new_

    构造方法

    class Foo:
        def __init__(self):
            print("执行init")
    
        def __new__(cls, *args, **kwargs):
            print("执行new")
            return object.__new__(cls)
    
    a = Foo()
    #############
    执行new
    执行init
    
    

    _del_

    析构方法,当对象在内存中被释放时,自动触发执行,在删除这个类创建的对象的时候会先触发这个方法,再删除对象,一般用于清理工作,比如说关闭文件,关闭网络的连接,数据库的连接

    class Foo:
        def __del__(self):
            print('执行我啦')
    
    f1=Foo()
    del f1
    print('------->')
    ###########
    执行我啦
    ------->
    
    
    
    class Foo:
        def __init__(self, filename):
            self.file = open(filename,mode="w",encoding="utf-8")
    
        def write(self):
            self.file.write("asddadsa")
    
        def __del__(self):
            self.file.close()
            print("执行了del")
    
    a = Foo("a.txt")
    print(a)
    del a
    

    _dict_

    类或对象中的所有成员

    class Foo:
        """这是类的doc"""
        country = "China"
        def __init__(self, name):
            self.name = name
    
    a = Foo("summer")
    print(Foo.__dict__)
    print(a.__dict__)
    
    #############
    {'__module__': '__main__', '__doc__': '这是类的doc', 'country': 'China', '__init__': <function Foo.__init__ at 0x10299d0d0>, '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>}
    {'name': 'summer'}
    

    类的反射

    反射:使用字符串数据类型的变量名来获取这个变量的值
    hasattr(obj,name) 判断对象中有没有name这个字符串后者属性
    getattr(obj,name) 获取对象中的name
    setattr(obj,name,summer) 添加,修改对象的属性值

    class Foo:
        def __init__(self,name):
            self.name = name
    
    p = Foo("summer")
    print(hasattr(p,"name"))  #判断对象中有没有name这个字符串后者属性
    print(getattr(p,"name")) #获取对象中的name,没有则报错
    setattr(p,"age",18) #添加,修改对象的属性值
    print(p.__dict__) #{'name': 'summer', 'age': 18}
    

    反射模块中的变量

    import sys
    print(sys.modules[__name__])
    import sys
    a = 1
    b = 2
    def bar():
        print("bar")
    print(getattr(sys.modules[__name__], "a"))
    print(getattr(sys.modules[__name__], "b"))
    getattr(sys.modules[__name__], "bar")()
    
    ##########
    <module '__main__' from '/Users/summer/PycharmProjects/s1/第四周周天/01.py'>
    1
    2
    bar
    
    
    #### \__getattr__\__setattr__\__delattr__
    
    __getattr__只有在使用点调用属性且属性不存在的时候才会触发
    __setattr__使用点添加/修改属性会触发它的执行
    __delattr__使用点删除属性的时候会触发
    ```python
    class Foo:
        def __init__(self,name):
            self.name = name
    
        def __getattr__(self, item):
            print("没有item这个属性就会执行")
    
        def __setattr__(self, key, value):
            print("通过obj.key执行")
            self.__dict__[key] = value  #没有这个赋值操作,永远都无法赋值
    
        def __delattr__(self, item):
            print("通过del obj.item执行")
            self.__dict__.pop(item) #实际的删除操作
    
    p = Foo("summer")
    p.name  #通过obj.key执行
    p.age = 18 #通过obj.key执行
    print(p.__dict__) #{'name': 'summer', 'age': 18}
    del p.age #通过del obj.item执行
    p.sex #没有item这个属性就会执行
    

    _setitem__getitem_delitem

    使用字符串调用属性时触发

    class Foo:
        def __init__(self,name):
            self.name = name
    
        def __getattr__(self, item):
            print("没有item这个属性就会执行")
    
        def __setattr__(self, key, value):
            print("通过obj.key执行")
            self.__dict__[key] = value  #没有这个赋值操作,永远都无法赋值
    
        def __delattr__(self, item):
            print("通过del obj.item执行")
            self.__dict__.pop(item) #实际的删除操作
    
        def __getitem__(self, item):
            print("使用obj[item]时执行")
            return self.__dict__[item]
    
        def __setitem__(self, key, value):
            print("使用obj[key]是执行")
            self.__dict__[key] = value
    
        def __delitem__(self, key):
            print("del obj[key]是执行")
            self.__dict__.pop(key)
    
    p = Foo("summer")
    p["name"]  #使用obj[item]时执行
    p["age"] = 18  #使用obj[key]是执行
    print(p.__dict__)  #{'name': 'summer', 'age': 18}
    del p["age"] #del obj[key]是执行
    

    _str__与__repr_

    当打印一个对象的时候触发,repr是str的备胎,有str就执行str,没有str的时候就执行repr

    class Foo:
        def __str__(self):
            return "执行str"
    
        def __repr__(self):
            return "没有str的时候执行我"
    a = Foo()
    print(a) #执行str
    print(str(a)) #执行str
    print(repr(a)) #没有str的时候执行我
    
    当你使用格式化%s的时候也会触发 
    print("%s" %a)
    str强转数据类型的时候 
    str(a)
    

    在继承的时候如何如果子类没有str,含有repr,但是父类中有str,那么会执行父类的str,父类中也没有str,才会执行自己的repr

    class Foo:
        def __str__(self):
            return "Foo的str"
    
        def __repr__(self):
            return "Foo的repr"
    
    class Son(Foo):
        # def __str__(self):
        #     return "Son的str"
        def __repr__(self):
            return "Son的repr"
    
    a = Son()
    print(a) #Foo的str
    

    _doc_

    类的描述信息,无法继承

    class Foo:
        """这是Foo的doc"""
        pass
    
    class Son(Foo):
        pass
    print(Foo.__doc__)
    print(Son.__doc__) ##该属性无法继承给子类
    
    这是Foo的doc
    None
    
    _call_

    对象加括号的时候执行

    class Foo:
        def __call__(self, *args, **kwargs):
            print("__call__方法")
    
    a = Foo()
    a() #__call__方法
    

    _module__与__class_

    _module_ 表示当前操作的对象在那个模块

    _class_ 表示当前操作的对象的类是什么

    class Foo:
        def __init__(self):
            pass
    a = Foo()
    print(Foo.__module__)
    print(a.__class__)
    
    __main__  #表示当前模块
    <class '__main__.Foo'>
    

    _slots_

    实例添加新的属性了,只能使用在__slots__中定义的那些属性名。

    class Foo:
        __slots__ = ["age","name","sex"]
        def __init__(self, name):
            self.name = name
    
        def say(self):
            print("hello %s" %self.name)
    
    a = Foo("summer")
    a.age = 18
    a.sex = "male"
    # print(a.__dict__) #AttributeError: 'Foo' object has no attribute '__dict__'
    a没有__dict__,统一归slots管,优化内存
    a.AAA = 1   #AttributeError: 'Foo' object has no attribute 'AAA'
    
  • 相关阅读:
    string_view暴力串串题
    字符串hash暴力串串题
    C++刷leetcode几点注意事项
    微软面试算法题(整理)
    Leetcode中的Dijkstra算法
    gdb在线调试多线程程序
    2022亚马逊校园招聘软件开发实习提前批面试题
    python模块tqdm(进度条)的使用
    解决 Failed while installing Dynamic Web Module
    最新eclipse从零开始建立SpringMVC项目(详细过程)
  • 原文地址:https://www.cnblogs.com/xiayuhao/p/9550364.html
Copyright © 2011-2022 走看看