AttributeError:'property'对象没有属性 [英] AttributeError: 'property' object has no attribute

查看:133
本文介绍了AttributeError:'property'对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python(2.6)看起来没有理由,任何人都可以看到这个代码的问题?

Python (2.6) seems to be derping for no reason, can anyone see a problem with this code?

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")

无效例外:


AttributeError:'property'object没有属性'doSomething'

AttributeError: 'property' object has no attribute 'doSomething'

理解一个属性在访问时会自动运行它的getter,所以为什么会抱怨一个属性对象,为什么不能找到我清楚可用的方法?

It was my understanding that a property would automatically run its getter when accessed, so why is it complaining about a property object, and why isn't it finding my clearly available method?

推荐答案

除了需要继承 object ,属性只能在实例上使用。

In addition to needing to inherit from object, properties only work on instances.

a = A()
a.db.doSomething("blah")

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

To make a property work on the class, you can define a metaclass. (A class is an instance of a metaclass, so properties defined on the metaclass work on the class, just as properties defined on a class work on an instance of that class.)

这篇关于AttributeError:'property'对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆