我正在寻找一种从其他类调用实例方法的方式,我想知道是否/如何能够执行以下操作
我正在编写的类是数据格式化程序,其__rshift__
方法应该能够将数据batch
的格式调整为许多数据库客户端,而无需用户更改方法用过的。这就是我希望调用>>
方法的方式
batch = SomeExtractor(config).extract("some")
db_client = InfluxDBClient()
# this would be awesome
DataFormater(batch)>>db_client.write_points
class DataFormater(object):
def __init__(self, batch: Batch):
self.batch = batch
@abstractmethod
def __rshift__(self, db):
db_client = some_way_to_get_the_called_client(db)
method = some_way_to_get_the_method(db)
if method == InfluxDBClient.write_points:
db_client.write_points({"measurement": self.batch.origin,
"time" : self.batch.date,
"tags": dict(zip(self.batch.dimensions_names, row["dimensions"])),
"fields": dict(zip(self.batch.metrics_names, row["values"])}
for row in self.batch.rows))
Google搜索我的问题,在stack = inspect.stack(db)
方法中添加了__rshift__
并得到了以下内容,但我不确定如何使用它
frame = <frame at 0x7f6c2a1515c0, file '/usr/src/collector/collector.py', line 95, code __rshift__>
context = <bound method InfluxDBClient.write_points of <collector.InfluxDBClient object at 0x7f6c2a131510>>
我该怎么做?
__self__
提出的优雅解决方案:class DataFormater(object):
def __init__(self, batch: Batch):
self.batch = batch
@abstractmethod
def __rshift__(self, db_method):
if type(db_method.__self__) == InfluxDBClient:
db_method( ({"measurement": self.batch.origin,
"time" : self.batch.date,
"tags": dict(zip(self.batch.dimensions_names, row["dimensions"])),
"fields": dict(zip(self.batch.metrics_names, row["values"]))}) for row in self.batch.rows )