小编sdo*_*obz的帖子

运算符可以作为python中的类方法重载吗?

为了使扩展看起来很干净,我试图在python中实现">>"运算符作为类方法.我不知道怎么回事.我不想创建一个实例,因为我真的在类本身上运行.

>>> class C:
...     @classmethod
...     def __rshift__(cls, other):
...         print("%s got %s" % (cls, other))
...
>>> C.__rshift__("input")
__main__.C got input
>>> C() >> "input"
__main__.C got input
>>> C >> "input"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'classobj' and 'str'
Run Code Online (Sandbox Code Playgroud)

背景资料:

我试图在peewee ORM中实现视图(类似于Django).Peewee允许您将数据库表及其关系定义为类,如下所示:

class Track(Model):
    title = CharField()
    artist = ForeignKeyField(Artist)

class Artist(Model):
    name = CharField(unique = True)
    location = ForeignKeyField(Location)

class Location(Model):
    state = CharField(size …
Run Code Online (Sandbox Code Playgroud)

python class operator-overloading peewee

6
推荐指数
1
解决办法
636
查看次数

标签 统计

class ×1

operator-overloading ×1

peewee ×1

python ×1