【问题标题】:Python How to call a class method without importingPython如何在不导入的情况下调用类方法
【发布时间】:2021-12-04 04:39:27
【问题描述】:

我在这个 repo 中找到了这段代码。 https://github.com/adw0rd/instagrapi/blob/master/instagrapi/mixins/fbsearch.py

我想知道如何调用self.private_request(),因为没有导入,并且在此类中没有定义private_request()

from instagrapi.extractors import extract_location


class FbSearchMixin:

    def fbsearch_places(self, query: str, lat: float = 40.74, lng: float = -73.94):
        params = {
            'search_surface': 'places_search_page',
            'timezone_offset': self.timezone_offset,
            'lat': lat,
            'lng': lng,
            'count': 30,
            'query': query,
        }
        result = self.private_request("fbsearch/places/", params=params)
        locations = []
        for item in result['items']:
            locations.append(extract_location(item['location']))
        return locations

如果有人能解释为什么以及如何做到这一点,我会很高兴。

【问题讨论】:

  • private_request 是 SAME 类中的另一个方法。
  • 不必在这个模块中定义,只要它是在有人使用它的上下文中定义的。这个类说它是一个mixin,所以大概它混合的任何东西都应该定义那个方法。
  • @balderman 同班?这对你意味着什么?文件中没有更多内容,也没有继承
  • @azro 据我了解,代码不能“按原样”运行

标签: python python-3.x oop methods python-requests


【解决方案1】:

这段代码没有调用fbsearch_places;只定义它。如果它在没有定义private_request 的情况下调用它,则会导致异常。

但如果有人导入此代码并将此类与另一个定义了private_request 的类结合使用,那么他们将能够使用fbsearch_places 方法。

这就是FbSearchMixin 中“混合”的意思:在多重继承中应该与另一个类结合使用的类。

【讨论】:

  • private_request() 在 private.py 中的 PrivateRequestMixin 类中定义
猜你喜欢
  • 2020-11-06
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多