Pergunta

I have following class in 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. 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')
Foi útil?

Solução

The SDK class is not a parent of the api class in your example, i.e. api does not inherit from SDK, they are merely nested.

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.

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.py:

URL = 'http://example.com'

def checkUrl(url):
    #some code

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

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.

See https://docs.python.org/2/tutorial/modules.html for details on how to use modules and packages.

Outras dicas

If you want a method to act as a classmethod, you have to tell python about it:

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. If it's just the namespace you care about, you'd typically use a module.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top