Python 对象属性具有<;类型';财产'&燃气轮机;

Python 对象属性具有<;类型';财产'&燃气轮机;,python,python-2.7,properties,Python,Python 2.7,Properties,我有一个定义了string属性的类 类Foo(对象): @财产 def种类(自我): 返回“bar” 我想将此属性传递给某个第三方代码,该代码断言该属性是str: 第三方: def baz(kind): if not isinstance(kind, (str, unicode)): message = ('%.1024r has type %s, but expected one of: %s' % (kind, type(kin

我有一个定义了string属性的类

类Foo(对象):
@财产
def种类(自我):
返回“bar”
我想将此属性传递给某个第三方代码,该代码断言该属性是
str

第三方:

def baz(kind):
    if not isinstance(kind, (str, unicode)):
        message = ('%.1024r has type %s, but expected one of: %s' %
                   (kind, type(kind), (str, unicode)))
        raise TypeError(message)
我:

输出:

TypeError: <property object at 0x11013e940> has type <type 'property'>, but expected one of: (<type 'str'>, <type 'unicode'>)

正如下面Martijn Pieters指出的那样。

您直接在类上访问属性:

这是因为只有当属性绑定到实例时,它才会在访问时使用getter函数。当绑定到类时,
属性
对象将直接返回


另请参见

您直接在类上访问属性:

这是因为只有当属性绑定到实例时,它才会在访问时使用getter函数。当绑定到类时,
属性
对象将直接返回


另请参见

您的代码对我来说运行良好:

class Foo(object):
    @property
    def kind(self):
        return 'bar'

def baz(kind):
    if not isinstance(kind, (str, unicode)):
        message = ('%.1024r has type %s, but expected one of: %s' %
                   (kind, type(kind), (str, unicode)))
        raise TypeError(message)


foo = Foo()
print foo.kind

baz(foo.kind)


--output:--
bar

你的代码对我来说很好:

class Foo(object):
    @property
    def kind(self):
        return 'bar'

def baz(kind):
    if not isinstance(kind, (str, unicode)):
        message = ('%.1024r has type %s, but expected one of: %s' %
                   (kind, type(kind), (str, unicode)))
        raise TypeError(message)


foo = Foo()
print foo.kind

baz(foo.kind)


--output:--
bar
是的,我的问题是错误的——我确实是从类而不是从实例访问方法。很好,是的,我的问题错了——我确实是从类而不是从实例访问该方法。抢手货
>>> Foo.kind
<property object at 0x104a22c00>
>>> baz(Foo.kind)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in baz
TypeError: <property object at 0x104a22c00> has type <type 'property'>, but expected one of: (<type 'str'>, <type 'unicode'>)
>>> Foo().kind
'bar'
>>> baz(Foo().kind)
class Foo(object):
    @property
    def kind(self):
        return 'bar'

def baz(kind):
    if not isinstance(kind, (str, unicode)):
        message = ('%.1024r has type %s, but expected one of: %s' %
                   (kind, type(kind), (str, unicode)))
        raise TypeError(message)


foo = Foo()
print foo.kind

baz(foo.kind)


--output:--
bar