【问题标题】:How to access a constructor in a staticmethod in python?如何在python的静态方法中访问构造函数?
【发布时间】:2021-02-21 22:04:34
【问题描述】:

我正在尝试访问 staticmethod 中的类实例,但我在这样做时遇到了困难。这是我的课:

class Worker:
    def __init__(self, ch, method, properties, body):
        self.ch = ch
        self.method = method
        self.properties = properties
        self.body = body

    @staticmethod
    def receive_payload_and_validate_schema(body):
        # some logic

        return body

    @staticmethod
    def some_func(id_info, partner_params):
        id_response = {}
        # some logic
        self.ch.basic_ack(delivery_tag=self.method.delivery_tag) # This is where the problem is

        return id_response

    @staticmethod
    def another_func(body):
        id_info = {} # assume it contains keys and values
        partner_params = {} # assume it contains keys and values
        # some logic
        return Worker.some_func(id_info, partner_params)

如何在 some_func 静态方法中使用这个表达式 self.ch.basic_ack(delivery_tag=self.method.delivery_tag)

【问题讨论】:

    标签: python flask rabbitmq pika


    【解决方案1】:

    根据定义,静态方法与类的实例无关。 some_func 不应该是静态的,或者ch 也应该是静态的。

    【讨论】:

      【解决方案2】:

      您不能使用静态方法。在您的代码中,您引用了 self,它永远不会传递给静态方法。

      self.ch.basic_ack(delivery_tag=self.method.delivery_tag)
      

      在 Python OOP 中,当调用标准方法时,调用该方法的对象作为第一个参数传递。传统上这称为self。在上一行中,您使用的是self,但它没有引用。

      【讨论】:

        猜你喜欢
        • 2011-12-29
        • 1970-01-01
        • 1970-01-01
        • 2020-10-26
        • 1970-01-01
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多