繁体   English   中英

实例化类时自动调用方法

[英]Auto call a method upon instantiating a class

我有一个这段代码:

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 

我希望在创建类的实例时自动运行log_in方法,例如:

  print Alluris('username', 'password')

输出应为:

Logged in successfully

要么

Incorrect username or password

基本上我不log_in这样手动运行log_in方法

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

编辑:我尝试将self.log_in()放在__init__方法中,但它仅返回类对象。

您可以通过在__init__方法中调用该方法来做到这一点:

class Alluris(object):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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