通用做法。 @six.add_metaclass(MetaClass) 的作用是在不同版本的Python之间提供一个优雅的声明类的metaclass的手段,事实上不用它也可以,只是使用了它代码更为整洁明了。 | import six @six.add_metaclass(Meta) class MyClass(object): pass |
在Python 3 等价于 | import six class MyClass(object, metaclass = Meta): pass |
在Python 2.x (x >= 6)中等价于 | import six class MyClass(object): __metaclass__ = Meta pass |
或者直接调用装饰器, 这里也能看出来装饰器就是个方法包装而已。 | import six class MyClass(object): pass MyClass = six.add_metaclass(Meta)(MyClass) |
import abc import six @six.add_metaclass(abc.ABCMeta) class BaseClass(object): @abc.abstractmethod def func_a(self, data): """ an abstract method need to be implemented """ @abc.abstractmethod def func_b(self, data): """ another abstract method need to be implemented """ class SubclassImpl(BaseClass): def func_a(self, data): print("Overriding func_a, " + str(data)) @staticmethod def func_d(self, data): print(type(self) + str(data)) class RegisteredImpl(object): @staticmethod def func_c(data): print("Method in third-party class, " + str(data)) BaseClass.register(RegisteredImpl) if __name__ == '__main__': for subclass in BaseClass.__subclasses__(): print("subclass of BaseClass: " + subclass.__name__) print("subclass do not contains RegisteredImpl") print("-----------------------------------------------") print("RegisteredImpl is subclass: " + str(issubclass(RegisteredImpl, BaseClass))) print("RegisteredImpl object is instance: " + str(isinstance(RegisteredImpl(), BaseClass))) print("SubclassImpl is subclass: " + str(issubclass(SubclassImpl, BaseClass))) print("-----------------------------------------------") obj1 = RegisteredImpl() obj1.func_c("RegisteredImpl new object OK!") print("-----------------------------------------------") obj2 = SubclassImpl() #由于没有实例化所有的方法,所以这里会报错 Can't instantiate abstract class SubclassImpl with abstract methods func_b obj2.func_a("It's right!") |
结果如下: subclass of BaseClass: SubclassImpl subclass do not contains RegisteredImpl ----------------------------------------------- RegisteredImpl is subclass: True RegisteredImpl object is instance: True SubclassImpl is subclass: True ----------------------------------------------- Method in third-party class, RegisteredImpl new object OK! ----------------------------------------------- Traceback (most recent call last): File "/Users/wangqi/Git/Python/scrapy_crawler_learn/test/ABCTest.py", line 51, in <module> obj2 = SubclassImpl() #由于没有实例化所有的方法,所以这里会报错 Can't instantiate abstract class SubclassImpl with abstract methods func_b TypeError: Can't instantiate abstract class SubclassImpl with abstract methods func_b |
1. #我们去检查某个类是否有某种方法
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __len__(self):
return len(self.employee)
com = Company(["bobby1","bobby2"])
print(hasattr(com, "__len__"))
class A:
pass
class B:
pass
2. #我们在某些情况之下希望判定某个对象的类型
from collections.abc import Sized
isinstance(com, Sized)
b = B()
print(isinstance(b, A))
# print(len(com))
3.
#我们需要强制某个子类必须实现某些方法
#实现了一个web框架,集成cache(redis, cache, memorychache)
#需要设计一个抽象基类, 指定子类必须实现某些方法
#如何去模拟一个抽象基类
import abc
from collections.abc import *
class CacheBase(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get(self, key):
pass
@abc.abstractmethod
def set(self, key, value):
pass
# class CacheBase():
# def get(self, key):
# raise NotImplementedError
# def set(self, key, value):
# raise NotImplementedError
#
class RedisCache(CacheBase):
def set(self, key, value):
pass
# redis_cache = RedisCache()
# redis_cache.set("key", "value")