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))
面試題

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM