【问题标题】:Calling a class function from a class inside the class从类内部的类调用类函数
【发布时间】:2021-05-15 07:53:35
【问题描述】:

我有这个代码:

class CongressApi:
    class apiKeyError(Exception):
        pass

    class Member:
        def __init__(self):
            print("self.makeRequest()?") # want to call the makeRequest function in the external class

    def __init__(self, apiKey):
        self.key = apiKey

    def makeRequest(self, req):
        ret = requests.get(f"https://api.propublica.org/congress/v1/{req}", headers={"X-API-Key": self.key})
        return ret.content

我希望能够从 memeber 类中调用 makeRequest() 函数。这可能吗?

【问题讨论】:

  • 你需要一个实例,和往常一样。你为什么要嵌套这个类?
  • MemberCongressAPI之间没有特别的关系; Member 的实例无权访问 CongressAPI 方法。为什么类首先嵌套?这不是在 Python 中像在 Java 中那样的常见习惯用法,因为您可以轻松地在单个模块中定义多个类。
  • 你能澄清一下你期望代码做什么吗? makeRequestCongressApi 的方法; Member 不是 CongressApi,需要后者的实例才能正确调用其方法。 哪个 CongressAPI 实例应该新的Member 使用来调用makeRequest

标签: python python-3.x class


【解决方案1】:

像这样嵌套类在 Python 中并不常见。我会推荐这样的东西:

class CongressApi:
    def __init__(self, apiKey):
        self.key = apiKey

    def makeRequest(self, req):
        ret = requests.get(f"https://api.propublica.org/congress/v1/{req}", headers={"X-API-Key": self.key})
        return ret.content

class Member:
        def __init__(self, congress_api_key):
            self.C = CongressAPI(congress_api_key)
            print(f"{self.C.makeRequest()}")

class apiKeyError(Exception):
        pass # this is really unnecessary - it's easier just to implement try/except blocks at each point in the code where an exception might be triggered.

一般来说,分开你的类是个好习惯。

【讨论】:

    【解决方案2】:

    如果您希望内部类的实例方法能够访问外部类的实例方法,则内部类的实例需要访问外部类的实例。例如:

    class CongressApi:
    
        class Member:
            def __init__(self, api):
                api.makeRequest("bar")
    
        def __init__(self, apiKey):
            self.key = apiKey
    
        def makeRequest(self, req):
            print(f"making request {req} with apiKey {self.key}")
    
        def do_member_thing(self):
            member = self.Member(self)
    
    
    api = CongressApi("foo")
    api.do_member_thing()  # making request bar with apiKey foo
    

    请注意,这实际上并不是一种组织类的明智方式——通常内部类的目的是封装一些不依赖于外部类的状态,并进一步抽象出该实现来自外部类的其余实现。允许将内部类传递给外部类的引用,但从架构的角度来看,这也完全违背了目的。

    【讨论】:

      猜你喜欢
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 2023-04-03
      相关资源
      最近更新 更多