Class 属性 其中 space

Class property with space in it

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

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

根据方言,在 SQL 中,您通常可以使用 Person.[two words]Person.`two words` 等方式来执行此操作。在 python 中是否可以这样做?

可能是因为 class 命名空间在语言中不仅限于 identifiers (and this is intentional)。但是,除了 getattr 之外,没有其他语法可用于访问此类属性。

>>> 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 创建这样的属性。