Class property with space in it

Viewed 243

Is it possible to do something like the following in Python?

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

Depending on the dialect, in SQL you can usually do this with something like Person.[two words] or Person.`two words`, etc. Is it possible to do that in python?

1 Answers

It is possible in that a class namespace is not restricted to only identifiers (and this is intentional in the language). However, there is no syntax other than getattr for accessing such an attribute.

>>> 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!'

It is also possible to create such an attribute with setattr.

Related