AttributeError:'property'对象没有属性

Ben*_*Ben 5 python properties exception class object

Python(2.6)似乎无缘无故,任何人都可以看到这个代码有问题吗?

class DB ():
    def doSomething (self, str):
        print str

class A ():
    __db = DB()

    @staticmethod
    def getDB ():
        return A.__db

    db = property(getDB)


A.db.doSomething("blah")
Run Code Online (Sandbox Code Playgroud)

失败,例外情况:

AttributeError:'property'对象没有属性'doSomething'

我的理解是,一个属性在访问时会自动运行它的getter,那么为什么它会抱怨一个属性对象,为什么它找不到我明显可用的方法呢?

kin*_*all 12

除了需要继承之外object,属性仅适用于实例.

a = A()
a.db.doSomething("blah")
Run Code Online (Sandbox Code Playgroud)

要使属性在类上运行,可以定义元类.(类是元类的实例,因此在元类上定义的属性在类上工作,就像在类上定义的属性在该类的实例上工作一样.)