6

为了使扩展看起来非常干净,我试图在 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
4

1 回答 1

9

在元类上定义方法。

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

class C(object):
  __metaclass__ = MC

print C >> None
于 2012-05-27T10:24:55.113 回答