Python @具有抽象基类的classmethod

Python @具有抽象基类的classmethod,python,inheritance,abstract-class,Python,Inheritance,Abstract Class,我有一个抽象基类和子类,定义如下(Python 2.7): 这很好,这意味着基类\u DbObject无法实例化,因为它只有属性getter方法的抽象版本 try: dbObject = _DbObject() print "dbObject.ObjectType: " + dbObject.ObjectType except Exception, err: print 'ERROR:', str(err) 现在我可以做: entry = Entry() print

我有一个抽象基类和子类,定义如下(Python 2.7):

这很好,这意味着基类
\u DbObject
无法实例化,因为它只有属性getter方法的抽象版本

try:
    dbObject = _DbObject()
    print "dbObject.ObjectType: " + dbObject.ObjectType
except Exception, err:
    print 'ERROR:', str(err) 
现在我可以做:

entry = Entry()
print entry.ObjectType
访问
ObjectType
属性。然而,我想做的只是:

print Entry.ObjectType

然而,无论我在哪里尝试插入
@classmethod
,我都会得到一个错误
classmethod对象不是可调用的

问题不在于你的
ABC
,而在于一个简单的事实,python中没有
类属性,你必须自己创建它。事实上,这有一个好处。实际上,在ABC中使用它应该没有问题。

因此,Python中“属性”工作方式的魔力是使用描述符协议实现的——属性本身,如果一个强大的内置函数提供了一个适用于实例的描述符,而不是您所看到的类

因此,您需要一个“类属性”-内置的
属性不能提供,但描述符协议可以。描述符协议所说的是,每当从类中检索属性时,如果它是一个具有
\uuu get\uuu
方法的对象,则使用“self,instance,owner”调用该方法,如果从类中而不是从实例中检索,则“instance”参数设置为
None

顺便说一句,正如@Constantinius所说的,这和ABC根本没有关系,只是你想要一个“类属性”

print Entry.ObjectType
class classproperty(object):
    def __init__(self, func):
        self.func = func
    def __get__(self, instance, owner):
        return self.func(owner)


class Entry(_DbObject):
    _objectTypeID = 'ENTRY'

    def _GetObjectType(cls):
        return MyDatabaseModule.DoesSomethingWith(cls._objectTypeID)
    ObjectType = classproperty(_GetObjectType, None)