【问题标题】:Create syntactic sugar to define a variable as a class instance创建语法糖以将变量定义为类实例
【发布时间】:2018-02-08 11:52:18
【问题描述】:

我正在尝试创建自己的类,其行为类似于常规类型,如下所示:

class CustomType:
    def __init__(self, content):
        self.content = content
    def __str__(self):
        return self.content

这意味着我可以这样做:

a = CustomType("hi there")
print(a)  # 'hi there'

但问题是我必须使用a = CustomType("hi there")。有没有办法让我做类似a = /hi there\ 或类似的解决方案,让我创建自己的语法糖?

谢谢。

【问题讨论】:

  • 解析器没有办法知道去寻找那个
  • 不。除非你想破解源代码。

标签: python python-3.x class types syntactic-sugar


【解决方案1】:

没有。 Python 不支持创建新语法。

【讨论】:

    【解决方案2】:

    注意:我不建议这样做。

    你不能这样做,因为解析器不知道去寻找它,但如果你想要类似的东西,你可以创建一个自定义类,当除以字符串时返回 CustomType 的新实例:

    class CustomSyntax:
        def __truediv__(self, value):
            return CustomType(value)
    

    如果你有那个类的实例(我们称之为c),你可以在任何时候将它除以一个字符串,只要你想要一个CustomType的实例:

    a = c/'hi there'
    b = c/'hello world'
    

    但是,这有点奇怪,最好还是坚持使用常规构造函数。

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 2012-08-30
      • 2016-01-07
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      相关资源
      最近更新 更多