简体   繁体   中英

Auto call a method upon instantiating a class

I have a this code:

from selenium import webdriver
from bs4 import BeautifulSoup as BS
from types import NoneType 


class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def log_in(self):
        driver = 
webdriver.PhantomJS('C:\Users\V\Desktop\PY\web_scrape\phantomjs.exe')
        driver.get('https://alluris.han.nl')
        driver.find_element_by_id('username').send_keys(self.username)
        driver.find_element_by_id('password').send_keys(self.password)
        driver.find_element_by_xpath('//*
[@id="formfields"]/input[3]').click()
        soup = BS(driver.page_source, 'lxml')
        if type(soup.find('div', {'id' : 'errormessage'})) == NoneType:
            return 'Logged in successfully'
        else:
            return soup.find('div', {'id' : 'errormessage'}).text 

I want the log_in method to auto run when i create an instance of a class, for example:

  print Alluris('username', 'password')

Output should be :

Logged in successfully

Or

Incorrect username or password

Basically I don't want to run the log_in method manually like

 print Alluris('username', 'password').log_in()

EDIT: I tried putting self.log_in() in the __init__ method but it only return the class object.

You can do that by calling the method in your __init__ method:

class Alluris(object):

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.log_in()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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