Can an operator be overloaded as a class method in python?

To make the extension really clean, I am trying to implement the "β†’" operator in python as a class method. I am not sure how to do this. I do not want to instantiate, since I am really working on the class itself.

>>> 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' 

Background Information:

I am trying to implement views in peewee ORM (similar to Django). Peewee allows you to define database tables and their relationships as classes, for example:

 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() 

Note: for simplicity, the order is canceled.

I am trying to extend this with the implementation of representations. One of the hardest parts is an easy way to specify connections. So far I have implemented the following:

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

This is normal, but I really would like to exclude "." for further simplification:

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

Which would you rather use? Or both?

As a side note, can anyone think of a good way to indicate a reverse connection? Something like the following is a bit uncomfortable for me:

 class LocWithSong(View): state = Location >> "state" title = Location >> Track.title 
+4
source share
1 answer

Define a method in a metaclass .

 class MC(type): def __rshift__(self, other): return something(self, other) class C(object): __metaclass__ = MC print C >> None 
+5
source

Source: https://habr.com/ru/post/1414583/


All Articles