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?
Answers:
We don’t need to predefine class members in Python. They can be defined in the constructor.
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
...
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?
We don’t need to predefine class members in Python. They can be defined in the constructor.
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
...