【问题标题】:Referencing parent object instance from inner class从内部类引用父对象实例
【发布时间】:2018-09-05 20:49:24
【问题描述】:

我正在尝试创建一个语法友好的库,它不需要用户不断地传递凭据或键入多余或过多的语句。我的策略是专注于我希望库语法的外观,然后设计库以这种方式运行。我知道我可以实现以下内容:

api = Api(user="admin", pswd="blahblah")

new_order = api.Order()
new_order.status = "pending"
api.create(new_order)
api.order_assign_user(new_order, user)

existing_order = api.get_order(orderId=12345)
existing_order.status = "shipped"
api.update(existing_order)

使用类似下面的东西:

class Api(object):
    def __init__(self, user=None, pswd=None):
        self.user = user
        self.pswd = pswd

    class Order(api):
        def __init__ (self, status=None):
            self.status = status

    def create(self, x):
        auth = Auth(self.user, self.pswd)
        # use authorization credentials to create data remotely
        return x

    def update(self, x):
        auth = Auth(self.user, self.pswd)
        # use authorization credentials to update data from remote
        return x

    def get_order(self, orderId=None):
        auth = Auth(self.user, self.pswd)
        # use authorization credentials to update data from remote
        return order

但我希望能够使用以下语句:

new_order.create() # instead of api.create(new_order)

new_order.assign_user(user) # instead of api.order_assign_user(new_order, user)

existing_order = api.Order.get(orderId=12345) # returns retrieved Order Instance

这给我带来了一个问题:

如何让Order() 实例访问创建它的Api() 实例的属性?如果无法访问这些,任何属性(如“user”和“pswd”)都将无法访问(requests.get() 调用需要它们)

我尝试了各种函数和类来完成此任务,但始终无法解决此问题。这是我能做到的最接近的:

class Api(object):
    def __init__(self, user=None, pswd=None):
        self.user = user
        self.pswd = pswd

    class Order(api):
        def __init__ (self, status=None):
            self.status = status

        @classmethod
        def get(cls, value):
            return cls(status=value)

        def create(self):
            auth = Auth(self.user, self.pswd) 
            # these credentials need to come from the Api() instance?, not self
            return x

        def update(self):
            auth = Auth(self.user, self.pswd) 
            # these credentials need to come from the Api() instance?, not self
            return x

这可能吗?还是我以错误的方式解决这个问题?我考虑过把它做成一个模块,但这似乎也不是一个有效的选择。

【问题讨论】:

  • 有可能,但我现在没时间给出正确的答案,如果还没有人发帖我会回来回答,同时看看__get__和@ 987654328@ 魔术方法以及它们如何接收instance 参数,您可以在Api 类中实例化您的Order 类并利用这些方法

标签: python python-3.x inner-classes


【解决方案1】:

这演示了我认为您想要做的基本实现,我发现这比我在评论您的问题时想到的__get____set__hackery 更好

import requests

class Order:
    def __init__(self, user:str, passwd: str):
        self.session = requests.Session()
        self.session.auth = (user, passwd)
        self.status = None

    # This is only to make the class callable, since the class is
    # already instantiated in Api init calling it again would raise an exception
    def __call__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
        return self

    def get(self):
        response = self.session.get('https://httpbin.org/basic-auth/my_user/my_pass')
        print(response.text)

    def post(self):
        response = self.session.post('https://httpbin.org/post', data={'status': self.status})
        print(response.text)


class Api:
    def __init__(self, user: str, passwd: str):
        self.Order = Order(user, passwd)

【讨论】:

  • 我能够使用它来完成我想要的。谢谢。
【解决方案2】:

Python 中的内部类只是单独的类,它们的实例不会以任何方式自动与外部类的实例关联。

我会建议一个解决方案,其中Order 的构造函数将Api 实例作为参数并使用该实例:

class Api(object):
    def __init__(self, user=None, pswd=None):
        self.user = user
        self.pswd = pswd

class Order(object):
    def __init__(self, api, status=None):
        self.api = api
        self.status = status

    @classmethod
    def get(cls, api, value):
        return cls(api, status=value)

    def create(self):
        auth = Auth(self.api.user, self.api.pswd)
        return x

    def update(self):
        auth = Auth(self.api.user, self.api.pswd)
        return x

【讨论】:

  • 这行得通,但是我必须输入Order.get(api, orderId=12345) 这虽然不是很成问题,但不是我想要实现的目标。虽然看起来像这样的事情最终可能会成为我的解决方案。
  • 如果我是你,我会在 Api 类中创建一个 get_order 方法,该方法将返回 Order(api=self, ...),然后按照该顺序工作。
  • 在不相关的注释中,camelCased 名称(如您评论中的 orderId)不是 Pythonic,您应该使用 snake_case
  • 我知道,但是为此创建的 API 使用 CamelCase 的属性(在 JSON 中)。我认为保持一致会更容易混淆,而且我不必在两者之间转换/交换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多