博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python之反射
阅读量:4355 次
发布时间:2019-06-07

本文共 15792 字,大约阅读时间需要 52 分钟。

isinstance和issubclass

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

class Foo:    passclass Son(Foo):    passs=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_moduledef demo1():    print('demo1')print(hasattr(demo1,'demo1'))
没在同一个文件下找模块
def demo1():    print('demo1')import sysmodule_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 fprint(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']=18f1['age1']=19del f1.age1del 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._instanceone = Singleton()two = Singleton()two.a = 3print(one.a)# 3# one和two完全相同,可以用id(), ==, is检测print(id(one))# 29097904print(id(two))# 29097904print(one == two)# Trueprint(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 Truea = 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 Truep_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:    passclass Son(Foo):    passs=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_moduledef demo1():    print('demo1')print(hasattr(demo1,'demo1'))
没在同一个文件下找模块
def demo1():    print('demo1')import sysmodule_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 fprint(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']=18f1['age1']=19del f1.age1del 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._instanceone = Singleton()two = Singleton()two.a = 3print(one.a)# 3# one和two完全相同,可以用id(), ==, is检测print(id(one))# 29097904print(id(two))# 29097904print(one == two)# Trueprint(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 Truea = 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 Truep_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:    passclass Son(Foo):    passs=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_moduledef demo1():    print('demo1')print(hasattr(demo1,'demo1'))
没在同一个文件下找模块
def demo1():    print('demo1')import sysmodule_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 fprint(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']=18f1['age1']=19del f1.age1del 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._instanceone = Singleton()two = Singleton()two.a = 3print(one.a)# 3# one和two完全相同,可以用id(), ==, is检测print(id(one))# 29097904print(id(two))# 29097904print(one == two)# Trueprint(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 Truea = 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 Truep_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:    passclass Son(Foo):    passs=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_moduledef demo1():    print('demo1')print(hasattr(demo1,'demo1'))
没在同一个文件下找模块
def demo1():    print('demo1')import sysmodule_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 fprint(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']=18f1['age1']=19del f1.age1del 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._instanceone = Singleton()two = Singleton()two.a = 3print(one.a)# 3# one和two完全相同,可以用id(), ==, is检测print(id(one))# 29097904print(id(two))# 29097904print(one == two)# Trueprint(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 Truea = 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 Truep_lst = []for i in range(84):    p_lst.append(Person('egon',i,'male'))print(p_lst)print(set(p_lst))
面试题

 

转载于:https://www.cnblogs.com/mengqingjian/p/7374385.html

你可能感兴趣的文章
oracle中的trunc()函数
查看>>
对大一一年的总结和对大二的规划
查看>>
结构化程序设计04 - 零基础入门学习Delphi13
查看>>
密码学基础
查看>>
Java基础Map接口+Collections工具类
查看>>
OSGI基础知识整理
查看>>
Revit 开发将自己的窗口设置为Revit窗口
查看>>
倾斜摄影数据OSGB转换成3DML(转载)
查看>>
给年轻程序员的几句话
查看>>
ionic如何uglify和minify你的js,css,image,png....
查看>>
[LeetCode]Minimum Depth of Binary Tree
查看>>
jboss初体验
查看>>
Python列表、元组练习
查看>>
angular页面刷新
查看>>
Leetcode:7- Reverse Integer
查看>>
C6表单(方成eform)---自定义流程标题格式
查看>>
GridView下DropDownList 的选择方法onselectedindexchanged 实现方法
查看>>
Python之set集合
查看>>
Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle
查看>>
Win7 下新版本Windows Virtual PC 安装SharePoint步骤详解
查看>>