从接口类调用实例方法

问题描述 投票:0回答:1

我正在寻找一种从其他类调用实例方法的方式,我想知道是否/如何能够执行以下操作

目标和背景

我正在编写的类是数据格式化程序,其__rshift__方法应该能够将数据batch的格式调整为许多数据库客户端,而无需用户更改方法用过的。这就是我希望调用>>方法的方式

batch  = SomeExtractor(config).extract("some")
db_client = InfluxDBClient()
# this would be awesome
DataFormater(batch)>>db_client.write_points

DataFormater

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

我该怎么做?

python design-patterns interface stack
1个回答
0
投票
@ sanyash使用__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 )

© www.soinside.com 2019 - 2024. All rights reserved.