简体   繁体   English

嵌套的Python类和对父方法的访问

[英]Nested Python class and access to parent's method

I have following class in Python: 我在Python中有以下类:

class SDK(object):
    URL = 'http://example.com'

    def checkUrl(self, url):
        #some code

    class api:
        def innerMethod(self, url):
            data = self.checkUrl(url)
            #rest of code

but when I try to access checkUrl from api, I get error. 但是当我尝试从api访问checkUrl时,我收到错误。 I try to call nested method by: 我尝试通过以下方式调用嵌套方法:

sdk = SDK()
sdk.api.innerMethod('http://stackoverflow.com')

Is there any simple way to call inner class methods, or (if not) structurize methods into inner objects? 有没有简单的方法来调用内部类方法,或者(如果没有)将方法结构化为内部对象? Any suggestion will be appreciated. 任何建议将不胜感激。

Edit: class code: 编辑:类代码:

class SDK(object):
    def run(self, method, *param):
        pass

    class api:
        def checkDomain(self, domain):
            json = self.run('check', domain)
            return json

run code: 运行代码:

sdk = SDK()
result = sdk.api().checkDomain('stackoverflow.com')

The SDK class is not a parent of the api class in your example, ie api does not inherit from SDK , they are merely nested. SDK类不是示例中api类的父类,即api不从SDK继承,它们仅仅是嵌套的。

Therefore the self object in your api.innerMethod method is only an instance of the api class and doesn't provide access to methods of the SDK class. 因此, api.innerMethod方法中的self对象只是api类的一个实例,不提供对SDK类方法的访问。

I strongly recommend getting more knowledgeable about object-oriented programming concepts and grasp what the issue is here. 我强烈建议您更多地了解面向对象的编程概念,并掌握这里的问题。 It will help you tremendously. 它会对你有很大的帮助。

As for using modules to achieve something along these lines, you can, for example, pull everything from the SDK class to sdk.py file, which would be the sdk module. 至于使用模块来实现这些方面的某些功能,例如,您可以将SDK类中的所有内容提取到sdk.py文件,该文件将是sdk模块。

sdk.py: sdk.py:

URL = 'http://example.com'

def checkUrl(url):
    #some code

class api:
    def innerMethod(self, url):
        data = checkUrl(url)
        #rest of code

main.py: main.py:

import sdk

api = sdk.api()
api.innerMethod('http://stackoverflow.com')

Or you may go even further and transform sdk to a package with api being a module inside it. 或者你可以更进一步,将sdk转换为api作为其中的模块的包。

See https://docs.python.org/2/tutorial/modules.html for details on how to use modules and packages. 有关如何使用模块和包的详细信息,请参阅https://docs.python.org/2/tutorial/modules.html

If you want a method to act as a classmethod, you have to tell python about it: 如果你想让一个方法充当类方法,你必须告诉python:

class SDK:
    class api:
         @classmethod
         def foo(cls):
                 return 1

Then you have access like 然后你就可以访问了

SDK.api.foo()

Depending on what you're trying to do, this smells kind of un-pythonic. 根据你想要做的事情,这会闻到一种非pythonic。 If it's just the namespace you care about, you'd typically use a module. 如果它只是您关心的命名空间,那么您通常会使用一个模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM