其中有空格的类属性

问题描述 投票:0回答:1

是否可以在Python中执行类似以下的操作?

class Object:
    
    def `two words`(self):
        return 'Worked!'

根据方言,在 SQL 中,您通常可以使用

Person.[two words]
Person.`two words`
等来完成此操作。在 python 中可以这样做吗?

python python-3.x python-internals
1个回答
5
投票

这是可能的。类命名空间不仅限于标识符,这是故意的。但是,在这种情况下,

instance.my attr
语法将不起作用,因此您必须使用
getattr(instance, "my attr")
来访问属性。

>>> def two_words(self):
...     return 'Worked!'
... 
>>> Object = type("Object", (), {"two words": two_words})
>>> obj = Object()
>>> "two words" in dir(obj)
True
>>> getattr(obj, "two words")
<bound method two_words of <__main__.Object object at 0x10d070ee0>>
>>> getattr(obj, "two words")()
'Worked!'

也可以使用

setattr
创建这样的属性。

© www.soinside.com 2019 - 2024. All rights reserved.