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

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

class Foo:
    def __init__(self,x):
        self.x = x

class SubFoo(Foo):
    def __init__(self):
        pass

f1 = Foo(2)
print(isinstance(f1,Foo)) # True
print(issubclass(SubFoo,Foo))  # True

 

__getattribute__

当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError

class Foo:
    def __init__(self,x):
        self.x=x

    def __getattribute__(self, item):
        print('不管是否存在,我都会执行')

f1=Foo(10)
f1.x
f1.xxxxxx
class Foo:
    def __init__(self,x):
        self.x = x
    def __getattr__(self, item):
        print("执行__getattr...")
        #return self.__dict__[item]
    def __getattribute__(self, item):
        print("不管是否存在,都会执行__getattribute...")
        raise AttributeError("%s not exit" %(item))

class SubFoo(Foo):
    def __init__(self):
        pass

f1 = Foo(2)
f1.x
f1.y

'''
不管是否存在,都会执行__getattribute...
执行__getattr...
不管是否存在,都会执行__getattribute...
执行__getattr...
'''

 

item

class Foo:
    def __init__(self,name):
        self.Name = name

    def __getitem__(self, item):
        print('__getitem__')
        return self.__dict__[item]
    def __setitem__(self, key, value):
        print('__setitem__')
        self.__dict__[key] = value
    def __delitem__(self, key):
        print('__delitem__')
        self.__dict__.pop(key)

f = Foo('lisi')
print(f.__dict__) # {'Name': 'lisi'}
f['age'] = 18 # __setitem__
print(f.__dict__) # {'Name': 'lisi', 'age': 18}

print(f['Name']) # __getitem__ lisi

del f['age'] # __delitem__

 

__str__,__repr__,__format__

改变对象的字符串显示__str__,__repr__

自定制格式化字符串__format__

class School:
    def __init__(self,name):
        self.name = name

    def __str__(self):
        return self.name

scl = School("CPU")
print(scl) # CPU
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-20
  • 2022-02-05
  • 2021-08-01
  • 2022-12-23
  • 2022-02-15
  • 2022-12-23
猜你喜欢
  • 2021-05-29
  • 2022-01-17
  • 2022-01-01
  • 2021-10-09
  • 2021-09-11
  • 2021-07-30
相关资源
相似解决方案