【问题标题】:Why does super().__init__() don´t work? OOP为什么 super().__init__() 不起作用?面向对象
【发布时间】:2021-04-30 07:41:03
【问题描述】:

我的问题是即使使用 super() 函数也没有加载来自父类的 self.client。相反,只有错误出现:

AttributeError:类型对象“AuthorizeOrder”没有属性“client”。

很遗憾,我在这里找不到任何错误,希望你们中的某个人知道我该如何解决这个问题。

非常感谢

class PayPalClient:

    def __init__(self):
        self.client_id = "XYZ"
        self.client_secret = "XYZ"
        self.environment = SandboxEnvironment(client_id=self.client_id, client_secret=self.client_secret)
        self.client = PayPalHttpClient(self.environment)

class AuthorizeOrder(PayPalClient):

    def __init__(self):
        super().__init__()

    @staticmethod
    def build_request_body():
        return {}

    @classmethod
    def authorize_order(self, order_id, debug=False):
        request = OrdersAuthorizeRequest(order_id)
        request.prefer("return=representation")
        request.request_body(self.build_request_body())
        response = self.client.execute(request)
        return response

【问题讨论】:

  • authorize_order@classmethod 尽管需要访问 instance 属性 - self 指的是类 AuthorizeOrder 而不是它的实例。另请注意,如果它只是要调用继承的实现(如__init__ 所做的那样),您可以完全省略一个方法。

标签: python oop paypal super


【解决方案1】:

问题不在于对super().__init__() 的调用。问题是您试图从类方法访问实例变量。传统上,类方法的第一个参数命名为 cls,并且是类本身,而不是类的实例。

有关classmethodstaticmethod 的更多详细信息,请参阅此答案:https://stackoverflow.com/a/12179752/3228591

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多