0

I am having a bit of trouble with nesting classes in python.

Mind you my code below is a simplified example showing what I want to do, but basically I want to use nested classes to make my code more structured and make sure I don't run into name clashes for certain functions.

See here my example code:

class Chrome:
 def __init__(self, url='http://localhost:4723/wd/hub'):
 # Capabilities
 capabilities = Capabilities.chrome()
 # Start session
 self.driver = webdriver.Remote(url, capabilities)
 def get_url(self, url):
 # Go to URL
 self.driver.get(url)
 class actions:
 @staticmethod
 def browse_url(url):
 # Go to url
 Chrome.get_url(url)
if __name__ == '__main__':
 browser = Chrome()
 browser.actions.browse_url('https://www.google.com')

The goal as you can see in if __name__ == '__main__' is to be able to start a browser instance, and then call functions in a structured way.

However I have no clue on how to correctly achieve the browser.actions.browse_url('https://www.google.com') concept.

How is this done correctly ?

asked Nov 12, 2016 at 20:05
2
  • What problem are you having? Error message? If so, what? Unexpected result? What are they? Commented Nov 12, 2016 at 20:12
  • @kindall error: TypeError: unbound method get_url() must be called with Chrome instance as first argument (got str instance instead) Commented Nov 12, 2016 at 20:14

1 Answer 1

1

You should call get_url from an instance of Chrome and not the class itself, since it's an instance method and not a static one:

...
@staticmethod
def browse_url(url):
 Chrome().get_url(url) 
...
if __name__ == '__main__':
 Chrome.actions.browse_url('https://www.google.com')
answered Nov 12, 2016 at 20:17
Sign up to request clarification or add additional context in comments.

8 Comments

Wouldn't this create a new instance every time? That's what I want to avoid.
@Snowlav Yes it would. Except you make it a static method, and then you'll have to figure another way to set up a driver for the class that is accessible by get_url
home can I share the same instance for every function then? I thought that's why I called browser = Chrome() at the start. I could say browser.get_url(url) in the function however that requires users to always use the variable browser to create the instance
Keep in mind that the action class is nested in the Chrome class and browse_url is static, so this makes it a little more complicated than you think
I don't think it's possible at all.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.