issubclass用于判断class是否是classinfo、或classinfo直接、间接的子类,返回值为布尔类型
class A:
pass
class B(A):
pass
class C(B):
pass
class D:
pass
x = C()
# x是C的直接的实例
print(isinstance(x, C))
# x是B的间接的实例
print(isinstance(x, B))
# x不是D的实例
print(isinstance(x, D))
# classinfo可以是一个元组
print(isinstance(x, (A, D)))
# C是B的直接子类
print(issubclass(C, B))
# C是A的间接子类
print(issubclass(C, A))
# C不是D的子类
print(issubclass(C, D))
class A:
def __init__(self):
print('in init function')
self.x = 1
def __new__(cls, *args, **kwargs):
print('in new function')
return object.__new__(A, *args, **kwargs)
单例模式:
一个类仅有一个对象。
class Singleton:
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = object.__new__(cls, *args, **kw)
return cls._instance
one = Singleton()
two = Singleton()
three = Singleton()
print(one,two,three)
class Foo:
def __init__(self):
self.name = 'jack'
self.age = 24
def __getitem__(self, item):
return self.__dict__[item]
def __setitem__(self, key, value):
self.__dict__[key] = value
def __delitem__(self, key):
del self.__dict__[key]
f = Foo()
print(f['name'])
f['name'] = 'bob'
del f['name']