简体   繁体   English

如何在类中调用函数?

[英]How to call a function within a class?

I need to call a function print3() which is inside the class two.我需要调用第二类中的函数print3() But I need to call from inside of the class but not being in any function:但我需要从类内部调用但不在任何函数中:

class two:
    y = 2

    def __init__(self):
        print('Login starts')
        self.dict ={'a':1, 'b':2, 'c':3, 'd':4}

    def print2(self, y):
        print(y)
        print(self.dict)

    def print3(self):
        print('print3')

    print3()

x = two()
x.print2(2)

The error i get is :我得到的错误是:

Traceback (most recent call last):
File "B:/data/loginMech/test 2.py", line 6, in <module>
class two:
File "B:/data/loginMech/test 2.py", line 22, in two
print3()
TypeError: print3() missing 1 required positional argument: 'self'

Also passing any value as self is also not a suitable answer.同样将任何值作为self传递也不是一个合适的答案。 It actually for a web scarping project that has:它实际上适用于具有以下功能的网络刮削项目:

from tkinter import *
import mechanicalsoup, random, re, json
# from termcolor import colored
from colorama import Fore,init, Back

init()

class Mygui:
    def window(self, colour='black'):
        loginClass = login()
        self.main_window=Tk()
        self.main_window.geometry('300x100')
        self.main_window.title('Login')
        self.top_frame=Frame(self.main_window)
        self.top_frame.pack()
        self.label=Label(self.top_frame, fg=colour, text="Your Cont", width=45)
        self.label.pack(side="top")
        self.label1=Label(self.top_frame,text=" ", width=45)
        self.label1.pack(side="top")
        self.my_button = Button(self.main_window, text="Retry", command=loginClass,  height=2, width=18)
        self.my_button.pack()

        mainloop()
    def do_something(self):
        print('ok')

class login:
    def __init__(self):
        print('Login starts')
        fp = open('dict.json', 'r')
        self.dict = json.load(fp)
        # key, pas = random.choice(list(dict.items()))
        # print(key, pas)
        self.browser = mechanicalsoup.StatefulBrowser()

    def webloading(self):
        print('webloading starts')

        key, pas = random.choice(list(self.dict.items()))
        # print(key, pas)
        try:
            self.browser.open("http://172.16.16.16:8090/")  # starting of login site
        except:
            print('No connection to Login Page')
            exit()
        self.browser.select_form('form[action="httpclient.html"]')
        self.browser.select_form('form[action="httpclient.html"]')  # form selection from the site
        # a = input('user ')
        # b = input('pass ')
        self.browser['username'] = key  # '1239'
        self.browser['password'] = pas  # ''
        response = self.browser.submit_selected()  # Response of login
        # sText = response.text

        msg = re.compile(r'<message><!\[CDATA\[(.*?)\]').findall(response.text)[0]  # fetching login status using regex
        return msg, key



    print('Login Checking starts')
    msg, key = webloading()
    if msg == 'You have successfully logged in':
        print(Back.YELLOW + Fore.BLUE + 'Logged in with ' + key)
    else:
        webloading()

M = Mygui()
M.window('blue')

For this error I get is:对于这个错误,我得到的是:

Login Checking starts
Traceback (most recent call last):
File "B:/data/loginMech/pro2.py", line 26, in <module>
class login:
File "B:/data/loginMech/pro2.py", line 60, in login
msg, key = webloading()
TypeError: webloading() missing 1 required positional argument: 'self'

def print3() inside the class is just a declaration.类中的 def print3() 只是一个声明。 So when you call print3() inside class it doesn't know what it is.因此,当您在类中调用 print3() 时,它不知道它是什么。 You need to either call is as a instance method x.print3() or call print3()inside any other class method, say inside print2():您需要调用 is 作为实例方法 x.print3() 或在任何其他类方法中调用 print3() ,例如在 print2() 中:

Change改变

def print3(self):
     print('print3')

To

def print3():
     print('print3')

Note that def prin3(self) means that it needs to be called by an object or class if the method is static.请注意, def prin3(self)意味着如果方法是静态的,则它需要由对象或类调用。

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

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