2015-03-31 38 views
-3
class Event(metaclass=ABCMeta): 

    def __init__(self): 
     self.type = self.get_full_type() 

    @classmethod 
    def get_full_type(cls): 
     return None 

    def as_dict(self): 
     return self.__dict__ 


class BaseEvent(Event, metaclass=ABCMeta): 

    SUB_TYPE = '' 

    @classmethod 
    def get_base_type(cls): 
     return super().get_full_type() 

    @classmethod 
    def get_full_type(cls): 
     base_type = cls.get_base_type() 
     if base_type: 
      return '.'.join([base_type, cls.SUB_TYPE]) 
     else: 
      return cls.SUB_TYPE 

在这里,您可以看到我尝试使类代表一些抽象事件。这里至关重要的是区分事件类型的能力。所以每个事件都有它的类型和基类型。完整类型是基本类型+子类型。如何使这段代码在python 2中工作

这给像这样定义

class MockEvent(BaseEvent): 

    SUB_TYPE = 'mock' 

    def __init__(self, some_object): 
     super(self.__class__, self).__init__() 
     self.some_object = some_object 

新的事件类型的能力,所以该完整型镜像类层次结构ClassA.ClassB.ClassC等我想你明白了吧。

不幸的是,这是不使用Python 2

class Event(object): 
    __metaclass__ = ABCMeta 
    SUB_TYPE = None 
    def __init__(self): 
     self.type = self.get_full_type() 

    @classmethod 
    def get_base_type(cls): 
     return None 

    @classmethod 
    def get_full_type(cls): 
     base_type = cls.get_base_type() 
     if base_type: 
      return '.'.join([base_type, cls.SUB_TYPE]) 
     else: 
      return cls.SUB_TYPE 

    def as_dict(self): 
     return self.__dict__ 


class BaseEvent(Event): 
    __metaclass__ = ABCMeta 
    SUB_TYPE = '' 

    @classmethod 
    def get_base_type(cls): 
     return super(cls.__class__, cls).get_full_type() 

File "/opt/leos/code/event_service/events/EventBus.py", line 38, in get_base_type return super(cls.class, cls).get_full_type() AttributeError: 'super' object has no attribute 'get_full_type'

我怎样才能使这项工作?

+0

它什么时候发生这种错误? – thefourtheye 2015-03-31 11:54:19

+0

使'super()。get_full_type()'成为'super(self .__ class__,self).get_full_type()'? – adarsh 2015-03-31 11:55:03

+0

@thefourtheye我修改了这个问题来回答这个问题。 – user1685095 2015-03-31 11:57:34

回答

0
class Event(object): 
    __metaclass__ = ABCMeta 
    def __init__(self): 
     self.type = self.get_full_type() 

    @classmethod 
    def get_full_type(cls): 
     return None 

    def as_dict(self): 
     return self.__dict__ 


class BaseEvent(Event): 
    __metaclass__ = ABCMeta 
    SUB_TYPE = None 

    @classmethod 
    def get_full_type(cls): 
     super_type = cls.get_super_type() 
     base_type = super_type.get_full_type() 
     if base_type: 
      return '.'.join([base_type, cls.SUB_TYPE]) 
     else: 
      return cls.SUB_TYPE 

    @classmethod 
    def get_super_type(cls): 
     return cls.__base__ 

我需要自动获取基本类型。没有提及super(currectClass,self)中的当前类,所以我使用了cls。 基地它的工作正常。