How can I define complex class attributes that should really only be instantiated in the __init__ function of a Python class?

Question:

I have the following code:

class pb:
   #defines driver, session and url
    driver=???
    def __init__(self,testMode):
        options=webdriver.ChromeOptions()
        if testMode:
            #sets the self.driver to headless mode
            options.add_argument('--headless')
            options.add_argument('window-size=1600x1080')
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=options)
        self.session=requests.Session()
        self.driver.maximize_window()
        self.url_pages_blanches = 'https://www.pagesjaunes.fr/pagesblanches/recherche?ou='

How can I complete the part with the question marks?

Asked By: samuelnihoul

||

Answers:

We don’t need to predefine class members in Python. They can be defined in the constructor.

Answered By: samuelnihoul

It’s true that, as the other answer states, you don’t need to declare an instance variable in class body.

It is, though, a recommended practice to do so, especially if you aren’t alergic to the python type annotations 😉

https://peps.python.org/pep-0526/#class-and-instance-variable-annotations

I think it makes it clearer what attributes a class has:

# the convention is that class names are written in CapWords: https://peps.python.org/pep-0008/#class-names
class Pb:
    driver: webdriver.Chrome
    ...
Answered By: yjay
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.