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

时间:2012-05-27 10:21:46

标签: python class operator-overloading peewee

为了使扩展程序真正干净,我正在尝试实现“>>” 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'

背景资料:

我正在尝试在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 = 2)
    city = CharField()

注意:为了清楚起见,订单是相反的。

我正在尝试通过视图的实现来扩展它。其中一个最困难的部分是设置一个干净的方式来指示连接。到目前为止,我已经实现了以下内容:

class Song(View):
    title = Track.title
    artist = Track.artist >> "name"
    state = Track.artist >> "location" >> "state"

这没关系,但我真的想消除“。”进一步简化:

class Song(View):
    title = Track >> "title"
    artist = Track >> "artist" >> "name"
    state = Track >> "artist" >> "location" >> "state"

您更愿意使用哪种?或两者兼而有之?

作为附注,任何人都可以想出一个指示向后加入的好方法吗?像下面这样的东西对我来说有点尴尬:

class LocWithSong(View):
    state = Location >> "state"
    title = Location >> Track.title

1 个答案:

答案 0 :(得分:6)

定义方法on the metaclass

class MC(type):
  def __rshift__(self, other):
    return something(self, other)

class C(object):
  __metaclass__ = MC

print C >> None