【问题标题】:Class property with space in it带有空格的类属性
【发布时间】:2020-12-14 04:42:20
【问题描述】:

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

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

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

【问题讨论】:

    标签: python python-3.x python-internals


    【解决方案1】:

    类命名空间可能不仅限于identifiers(在语言中这是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 创建这样的属性。

    【讨论】:

    • 对,好吧,如果我需要保留该数据,我想我可能会像您一样映射一个空间或将其转换为_20_(也许还有其他代码点不受身份标识)。你知道那些标识符限制在 CPython 中是在哪里完成的吗?
    • 我猜应该是PyUnicode_IsIdentifier
    猜你喜欢
    • 2012-11-28
    • 1970-01-01
    • 2018-05-31
    • 2017-07-13
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    相关资源
    最近更新 更多