繁体   English   中英

创建语法糖以将变量定义为类实例

[英]Create syntactic sugar to define a variable as a class instance

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

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不支持创建新语法。

注意 :我不建议您这样做。

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

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

然后,如果您有该类的实例(我们称其为c ),则可以在需要CustomType实例的任何时候将其除以字符串:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM