-3

I need to call a function print3() which is inside the class two. 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. It actually for a web scraping 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'
Nishan Paudel
  • 125
  • 10
  • Possible duplicate of [Python call function within class](https://stackoverflow.com/questions/5615648/python-call-function-within-class) – caedmon Aug 23 '18 at 06:12
  • 1
    It may help if you tell why you need this. – bereal Aug 23 '18 at 06:12
  • What do you expect that to do? ``print3()` requires an instance, and none exists while you're still defining the class. – kindall Aug 23 '18 at 06:15
  • This is probably not what you want to do. Include the "Why" in your question so better solutions can be suggested. – thithien Aug 23 '18 at 06:18
  • When do you want the login to happen? If you want it to happen as soon as the class is initialised, write a login method and call it from __init__. Otherwise try to explain what sequence of events should happen, and when the login should occur as part of that. – Marius Aug 23 '18 at 06:24

2 Answers2

0

def print3() inside the class is just a declaration. So when you call print3() inside class it doesn't know what it is. You need to either call is as a instance method x.print3() or call print3()inside any other class method, say inside print2():

Kiran
  • 85
  • 1
  • 1
  • 5
0

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.

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • The last comment isn't entirely true. `self` is just a convention name: it doesn't exactly mean that it's going to be an object or a class for which it's going to be called, and it doesn't even need to be called `self` – marianosimone Aug 23 '18 at 15:14