• python之反射


    isinstance和issubclass

    isinstance(obj,cls)检查是否obj是否是类 cls 的对象

    class Foo:
        pass
    class Son(Foo):
        pass
    s=Son()
    
    print(isinstance(s,Son))

    issubclass(sub, super)检查sub类是否是 super 类的派生类 

    class Foo(object):
        pass
     
    class Bar(Foo):
        pass
     
    issubclass(Bar, Foo)

    反射

    python面向对象中的反射:通过字符串的形式操作对象相关的属性,python中一切事物都是对象(都可以用反射)

    下列方法适用于类和对象:

     检查是否含有某属性---hasattr 返回布尔值
    获取属性---getattr 没有就会报错
    设置属性---setattr
    删除属性---delattr
    class Foo:
        f = '类的静态变量'
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say_hi(self):
            print('hi,%s'%self.name)
    
    obj=Foo('egon',73)
    
    #检测是否含有某属性
    print(hasattr(obj,'name'))
    print(hasattr(obj,'say_hi'))
    
    #获取属性
    n=getattr(obj,'name')
    print(n)
    func=getattr(obj,'say_hi')
    func()
    
    print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
    
    #设置属性
    setattr(obj,'sb',True)
    setattr(obj,'show_name',lambda self:self.name+'sb')
    print(obj.__dict__)
    print(obj.show_name(obj))
    
    #删除属性
    delattr(obj,'age')
    delattr(obj,'show_name')
    delattr(obj,'show_name111')#不存在,则报错
    
    print(obj.__dict__)
    四个方法的使用
    
    
    class Foo(object):
     
        staticField = "old boy"
     
        def __init__(self):
            self.name = 'agg'
     
        def func(self):
            return 'func'
     
        @staticmethod
        def bar():
            return 'bar'
     
    print getattr(Foo, 'staticField')
    print getattr(Foo, 'func')
    print getattr(Foo, 'bar')
    类也是属性

    导入其他模块

    import my_module
    def demo1():
        print('demo1')
    print(hasattr(demo1,'demo1'))
    没在同一个文件下找模块
    def demo1():
        print('demo1')
    import sys
    module_obj=sys.modules[__name__]
    print(hasattr(module_obj,'demo1'))
    getattr(module_obj,'demo1')
    在一个文件下找模块
    改对象的字符串显示__str__和__repr__:
    %s和%r

    __del__

    class Foo:
        def __del__(self):
            print('fgs')
    f=Foo()
    print(123)
    print(123)
    del f
    print(123)
    print(123)
    print(123)
    del示范

    item系列

    __getitem__\__setitem__\__delitem__

    class Foo:
        def __init__(self,name):
            self.name=name
    
        def __getitem__(self, item):
            print(self.__dict__[item])
    
        def __setitem__(self, key, value):
            self.__dict__[key]=value
        def __delitem__(self, key):
            print('del obj[key]时,我执行')
            self.__dict__.pop(key)
        def __delattr__(self, item):
            print('del obj.key时,我执行')
            self.__dict__.pop(item)
    
    f1=Foo('sb')
    f1['age']=18
    f1['age1']=19
    del f1.age1
    del f1['age']
    f1['name']='alex'
    print(f1.__dict__)
    View Code

    __new__

    class A:
        def __init__(self):  #有一个方法在帮你创造self
            print('in init function')
            self.x=1
        def __new__(cls, *args, **kwargs):
            print('in init funct')
            return object.__new__(A,*args,**kwargs)
    a=A()
    View Code

    单例模式

    class Singleton:
        def __new__(cls, *args, **kw):
            if not hasattr(cls, '_instance'):
                orig = super(Singleton, cls)
                cls._instance = orig.__new__(cls, *args, **kw)
            return cls._instance
    
    one = Singleton()
    two = Singleton()
    
    two.a = 3
    print(one.a)
    # 3
    # one和two完全相同,可以用id(), ==, is检测
    print(id(one))
    # 29097904
    print(id(two))
    # 29097904
    print(one == two)
    # True
    print(one is two)
    View Code
    class Foo:
    
        def __init__(self):
            pass
        
        def __call__(self, *args, **kwargs):
    
            print('__call__')
    
    
    obj = Foo() # 执行 __init__
    obj()       # 执行 __call__
    __call__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __len__(self):
            return len(self.__dict__)
    a = A()
    print(len(a))
    __len__模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __hash__(self):
            return hash(str(self.a)+str(self.b))
    a = A()
    print(hash(a))
    __hash__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __eq__(self,obj):
            if  self.a == obj.a and self.b == obj.b:
                return True
    a = A()
    b = A()
    print(a == b)
    __eq__ 模式
    class Person:
        def __init__(self,name,age,sex):
            self.name = name
            self.age = age
            self.sex = sex
    
        def __hash__(self):
            return hash(self.name+self.sex)
    
        def __eq__(self, other):
            if self.name == other.name and self.sex == other.sex:return True
    
    
    p_lst = []
    for i in range(84):
        p_lst.append(Person('egon',i,'male'))
    
    print(p_lst)
    print(set(p_lst))
    面试题
     

    ---恢复内容结束---

    isinstance和issubclass

    isinstance(obj,cls)检查是否obj是否是类 cls 的对象

    class Foo:
        pass
    class Son(Foo):
        pass
    s=Son()
    
    print(isinstance(s,Son))

    issubclass(sub, super)检查sub类是否是 super 类的派生类 

    class Foo(object):
        pass
     
    class Bar(Foo):
        pass
     
    issubclass(Bar, Foo)

    反射

    python面向对象中的反射:通过字符串的形式操作对象相关的属性,python中一切事物都是对象(都可以用反射)

    下列方法适用于类和对象:

     检查是否含有某属性---hasattr 返回布尔值
    获取属性---getattr 没有就会报错
    设置属性---setattr
    删除属性---delattr
    class Foo:
        f = '类的静态变量'
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say_hi(self):
            print('hi,%s'%self.name)
    
    obj=Foo('egon',73)
    
    #检测是否含有某属性
    print(hasattr(obj,'name'))
    print(hasattr(obj,'say_hi'))
    
    #获取属性
    n=getattr(obj,'name')
    print(n)
    func=getattr(obj,'say_hi')
    func()
    
    print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
    
    #设置属性
    setattr(obj,'sb',True)
    setattr(obj,'show_name',lambda self:self.name+'sb')
    print(obj.__dict__)
    print(obj.show_name(obj))
    
    #删除属性
    delattr(obj,'age')
    delattr(obj,'show_name')
    delattr(obj,'show_name111')#不存在,则报错
    
    print(obj.__dict__)
    四个方法的使用
    
    
    class Foo(object):
     
        staticField = "old boy"
     
        def __init__(self):
            self.name = 'agg'
     
        def func(self):
            return 'func'
     
        @staticmethod
        def bar():
            return 'bar'
     
    print getattr(Foo, 'staticField')
    print getattr(Foo, 'func')
    print getattr(Foo, 'bar')
    类也是属性

    导入其他模块

    import my_module
    def demo1():
        print('demo1')
    print(hasattr(demo1,'demo1'))
    没在同一个文件下找模块
    def demo1():
        print('demo1')
    import sys
    module_obj=sys.modules[__name__]
    print(hasattr(module_obj,'demo1'))
    getattr(module_obj,'demo1')
    在一个文件下找模块
    改对象的字符串显示__str__和__repr__:
    %s和%r

    __del__

    class Foo:
        def __del__(self):
            print('fgs')
    f=Foo()
    print(123)
    print(123)
    del f
    print(123)
    print(123)
    print(123)
    del示范

    item系列

    __getitem__\__setitem__\__delitem__

    class Foo:
        def __init__(self,name):
            self.name=name
    
        def __getitem__(self, item):
            print(self.__dict__[item])
    
        def __setitem__(self, key, value):
            self.__dict__[key]=value
        def __delitem__(self, key):
            print('del obj[key]时,我执行')
            self.__dict__.pop(key)
        def __delattr__(self, item):
            print('del obj.key时,我执行')
            self.__dict__.pop(item)
    
    f1=Foo('sb')
    f1['age']=18
    f1['age1']=19
    del f1.age1
    del f1['age']
    f1['name']='alex'
    print(f1.__dict__)
    View Code

    __new__

    class A:
        def __init__(self):  #有一个方法在帮你创造self
            print('in init function')
            self.x=1
        def __new__(cls, *args, **kwargs):
            print('in init funct')
            return object.__new__(A,*args,**kwargs)
    a=A()
    View Code

    单例模式

    class Singleton:
        def __new__(cls, *args, **kw):
            if not hasattr(cls, '_instance'):
                orig = super(Singleton, cls)
                cls._instance = orig.__new__(cls, *args, **kw)
            return cls._instance
    
    one = Singleton()
    two = Singleton()
    
    two.a = 3
    print(one.a)
    # 3
    # one和two完全相同,可以用id(), ==, is检测
    print(id(one))
    # 29097904
    print(id(two))
    # 29097904
    print(one == two)
    # True
    print(one is two)
    View Code
    class Foo:
    
        def __init__(self):
            pass
        
        def __call__(self, *args, **kwargs):
    
            print('__call__')
    
    
    obj = Foo() # 执行 __init__
    obj()       # 执行 __call__
    __call__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __len__(self):
            return len(self.__dict__)
    a = A()
    print(len(a))
    __len__模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __hash__(self):
            return hash(str(self.a)+str(self.b))
    a = A()
    print(hash(a))
    __hash__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __eq__(self,obj):
            if  self.a == obj.a and self.b == obj.b:
                return True
    a = A()
    b = A()
    print(a == b)
    __eq__ 模式
    class Person:
        def __init__(self,name,age,sex):
            self.name = name
            self.age = age
            self.sex = sex
    
        def __hash__(self):
            return hash(self.name+self.sex)
    
        def __eq__(self, other):
            if self.name == other.name and self.sex == other.sex:return True
    
    
    p_lst = []
    for i in range(84):
        p_lst.append(Person('egon',i,'male'))
    
    print(p_lst)
    print(set(p_lst))
    面试题
     

    ---恢复内容开始---

    isinstance和issubclass

    isinstance(obj,cls)检查是否obj是否是类 cls 的对象

    class Foo:
        pass
    class Son(Foo):
        pass
    s=Son()
    
    print(isinstance(s,Son))

    issubclass(sub, super)检查sub类是否是 super 类的派生类 

    class Foo(object):
        pass
     
    class Bar(Foo):
        pass
     
    issubclass(Bar, Foo)

    反射

    python面向对象中的反射:通过字符串的形式操作对象相关的属性,python中一切事物都是对象(都可以用反射)

    下列方法适用于类和对象:

     检查是否含有某属性---hasattr 返回布尔值
    获取属性---getattr 没有就会报错
    设置属性---setattr
    删除属性---delattr
    class Foo:
        f = '类的静态变量'
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say_hi(self):
            print('hi,%s'%self.name)
    
    obj=Foo('egon',73)
    
    #检测是否含有某属性
    print(hasattr(obj,'name'))
    print(hasattr(obj,'say_hi'))
    
    #获取属性
    n=getattr(obj,'name')
    print(n)
    func=getattr(obj,'say_hi')
    func()
    
    print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
    
    #设置属性
    setattr(obj,'sb',True)
    setattr(obj,'show_name',lambda self:self.name+'sb')
    print(obj.__dict__)
    print(obj.show_name(obj))
    
    #删除属性
    delattr(obj,'age')
    delattr(obj,'show_name')
    delattr(obj,'show_name111')#不存在,则报错
    
    print(obj.__dict__)
    四个方法的使用
    
    
    class Foo(object):
     
        staticField = "old boy"
     
        def __init__(self):
            self.name = 'agg'
     
        def func(self):
            return 'func'
     
        @staticmethod
        def bar():
            return 'bar'
     
    print getattr(Foo, 'staticField')
    print getattr(Foo, 'func')
    print getattr(Foo, 'bar')
    类也是属性

    导入其他模块

    import my_module
    def demo1():
        print('demo1')
    print(hasattr(demo1,'demo1'))
    没在同一个文件下找模块
    def demo1():
        print('demo1')
    import sys
    module_obj=sys.modules[__name__]
    print(hasattr(module_obj,'demo1'))
    getattr(module_obj,'demo1')
    在一个文件下找模块
    改对象的字符串显示__str__和__repr__:
    %s和%r

    __del__

    class Foo:
        def __del__(self):
            print('fgs')
    f=Foo()
    print(123)
    print(123)
    del f
    print(123)
    print(123)
    print(123)
    del示范

    item系列

    __getitem__\__setitem__\__delitem__

    class Foo:
        def __init__(self,name):
            self.name=name
    
        def __getitem__(self, item):
            print(self.__dict__[item])
    
        def __setitem__(self, key, value):
            self.__dict__[key]=value
        def __delitem__(self, key):
            print('del obj[key]时,我执行')
            self.__dict__.pop(key)
        def __delattr__(self, item):
            print('del obj.key时,我执行')
            self.__dict__.pop(item)
    
    f1=Foo('sb')
    f1['age']=18
    f1['age1']=19
    del f1.age1
    del f1['age']
    f1['name']='alex'
    print(f1.__dict__)
    View Code

    __new__

    class A:
        def __init__(self):  #有一个方法在帮你创造self
            print('in init function')
            self.x=1
        def __new__(cls, *args, **kwargs):
            print('in init funct')
            return object.__new__(A,*args,**kwargs)
    a=A()
    View Code

    单例模式

    class Singleton:
        def __new__(cls, *args, **kw):
            if not hasattr(cls, '_instance'):
                orig = super(Singleton, cls)
                cls._instance = orig.__new__(cls, *args, **kw)
            return cls._instance
    
    one = Singleton()
    two = Singleton()
    
    two.a = 3
    print(one.a)
    # 3
    # one和two完全相同,可以用id(), ==, is检测
    print(id(one))
    # 29097904
    print(id(two))
    # 29097904
    print(one == two)
    # True
    print(one is two)
    View Code
    class Foo:
    
        def __init__(self):
            pass
        
        def __call__(self, *args, **kwargs):
    
            print('__call__')
    
    
    obj = Foo() # 执行 __init__
    obj()       # 执行 __call__
    __call__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __len__(self):
            return len(self.__dict__)
    a = A()
    print(len(a))
    __len__模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __hash__(self):
            return hash(str(self.a)+str(self.b))
    a = A()
    print(hash(a))
    __hash__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __eq__(self,obj):
            if  self.a == obj.a and self.b == obj.b:
                return True
    a = A()
    b = A()
    print(a == b)
    __eq__ 模式
    class Person:
        def __init__(self,name,age,sex):
            self.name = name
            self.age = age
            self.sex = sex
    
        def __hash__(self):
            return hash(self.name+self.sex)
    
        def __eq__(self, other):
            if self.name == other.name and self.sex == other.sex:return True
    
    
    p_lst = []
    for i in range(84):
        p_lst.append(Person('egon',i,'male'))
    
    print(p_lst)
    print(set(p_lst))
    面试题
     

    ---恢复内容结束---

    isinstance和issubclass

    isinstance(obj,cls)检查是否obj是否是类 cls 的对象

    class Foo:
        pass
    class Son(Foo):
        pass
    s=Son()
    
    print(isinstance(s,Son))

    issubclass(sub, super)检查sub类是否是 super 类的派生类 

    class Foo(object):
        pass
     
    class Bar(Foo):
        pass
     
    issubclass(Bar, Foo)

    反射

    python面向对象中的反射:通过字符串的形式操作对象相关的属性,python中一切事物都是对象(都可以用反射)

    下列方法适用于类和对象:

     检查是否含有某属性---hasattr 返回布尔值
    获取属性---getattr 没有就会报错
    设置属性---setattr
    删除属性---delattr
    class Foo:
        f = '类的静态变量'
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say_hi(self):
            print('hi,%s'%self.name)
    
    obj=Foo('egon',73)
    
    #检测是否含有某属性
    print(hasattr(obj,'name'))
    print(hasattr(obj,'say_hi'))
    
    #获取属性
    n=getattr(obj,'name')
    print(n)
    func=getattr(obj,'say_hi')
    func()
    
    print(getattr(obj,'aaaaaaaa','不存在啊')) #报错
    
    #设置属性
    setattr(obj,'sb',True)
    setattr(obj,'show_name',lambda self:self.name+'sb')
    print(obj.__dict__)
    print(obj.show_name(obj))
    
    #删除属性
    delattr(obj,'age')
    delattr(obj,'show_name')
    delattr(obj,'show_name111')#不存在,则报错
    
    print(obj.__dict__)
    四个方法的使用
    
    
    class Foo(object):
     
        staticField = "old boy"
     
        def __init__(self):
            self.name = 'agg'
     
        def func(self):
            return 'func'
     
        @staticmethod
        def bar():
            return 'bar'
     
    print getattr(Foo, 'staticField')
    print getattr(Foo, 'func')
    print getattr(Foo, 'bar')
    类也是属性

    导入其他模块

    import my_module
    def demo1():
        print('demo1')
    print(hasattr(demo1,'demo1'))
    没在同一个文件下找模块
    def demo1():
        print('demo1')
    import sys
    module_obj=sys.modules[__name__]
    print(hasattr(module_obj,'demo1'))
    getattr(module_obj,'demo1')
    在一个文件下找模块
    改对象的字符串显示__str__和__repr__:
    %s和%r

    __del__

    class Foo:
        def __del__(self):
            print('fgs')
    f=Foo()
    print(123)
    print(123)
    del f
    print(123)
    print(123)
    print(123)
    del示范

    item系列

    __getitem__\__setitem__\__delitem__

    class Foo:
        def __init__(self,name):
            self.name=name
    
        def __getitem__(self, item):
            print(self.__dict__[item])
    
        def __setitem__(self, key, value):
            self.__dict__[key]=value
        def __delitem__(self, key):
            print('del obj[key]时,我执行')
            self.__dict__.pop(key)
        def __delattr__(self, item):
            print('del obj.key时,我执行')
            self.__dict__.pop(item)
    
    f1=Foo('sb')
    f1['age']=18
    f1['age1']=19
    del f1.age1
    del f1['age']
    f1['name']='alex'
    print(f1.__dict__)
    View Code

    __new__

    class A:
        def __init__(self):  #有一个方法在帮你创造self
            print('in init function')
            self.x=1
        def __new__(cls, *args, **kwargs):
            print('in init funct')
            return object.__new__(A,*args,**kwargs)
    a=A()
    View Code

    单例模式

    class Singleton:
        def __new__(cls, *args, **kw):
            if not hasattr(cls, '_instance'):
                orig = super(Singleton, cls)
                cls._instance = orig.__new__(cls, *args, **kw)
            return cls._instance
    
    one = Singleton()
    two = Singleton()
    
    two.a = 3
    print(one.a)
    # 3
    # one和two完全相同,可以用id(), ==, is检测
    print(id(one))
    # 29097904
    print(id(two))
    # 29097904
    print(one == two)
    # True
    print(one is two)
    View Code
    class Foo:
    
        def __init__(self):
            pass
        
        def __call__(self, *args, **kwargs):
    
            print('__call__')
    
    
    obj = Foo() # 执行 __init__
    obj()       # 执行 __call__
    __call__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __len__(self):
            return len(self.__dict__)
    a = A()
    print(len(a))
    __len__模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __hash__(self):
            return hash(str(self.a)+str(self.b))
    a = A()
    print(hash(a))
    __hash__ 模式
    class A:
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __eq__(self,obj):
            if  self.a == obj.a and self.b == obj.b:
                return True
    a = A()
    b = A()
    print(a == b)
    __eq__ 模式
    class Person:
        def __init__(self,name,age,sex):
            self.name = name
            self.age = age
            self.sex = sex
    
        def __hash__(self):
            return hash(self.name+self.sex)
    
        def __eq__(self, other):
            if self.name == other.name and self.sex == other.sex:return True
    
    
    p_lst = []
    for i in range(84):
        p_lst.append(Person('egon',i,'male'))
    
    print(p_lst)
    print(set(p_lst))
    面试题
  • 相关阅读:
    kafka cdh 安装
    【转】Public key for *.rpm is not installed,使用yum安装时报错
    12.yaml的简单使用
    python基础教程第三版阅读笔记(一)
    Python库文件安装失败问题及解决方式汇总-持续更新ing~
    taiko初体验
    VMware之USB设备连接
    C++之DLL的动态加载与静态加载初尝试
    C++课堂练习二
    C++课堂练习三
  • 原文地址:https://www.cnblogs.com/mengqingjian/p/7374385.html
Copyright © 2020-2023  润新知