Katie010203
Katie010203

Reputation: 25

Calling function from a class from the main code

I created a code using just functions. I am now putting the functions into classes.

I created the function:

    def login()
        login_button = Button(root, text="Click here to enter data: ",
                              command=lambda: validation(username_input_box.get(), password_input_box.get()))

        login_button.place(x=210, y=240)

        quit_button = Button(root, text="Quit", command=root.quit)
        quit_button.place(x=265, y=300)

I have now put it in a class called "setup" (the class has other function):

class setup:
    def login(self):
        login_button = Button(root, text="Click here to enter data: ",
                              command=lambda: self.validation(username_input_box.get(), password_input_box.get()))

        login_button.place(x=210, y=240)

        quit_button = Button(root, text="Quit", command=root.quit)
        quit_button.place(x=265, y=300)

I want to call the function login() from outside the class. I know normally you would just do login(), but It says "login" is not defined. Any idea on how to do this?

thanks x

Upvotes: 0

Views: 32

Answers (2)

Sahadat Hossain
Sahadat Hossain

Reputation: 4349

To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below.

class setup:
    def login(self):
        login_button = Button(root, text="Click here to enter data: ",
                              command=lambda: self.validation(username_input_box.get(), password_input_box.get()))

        login_button.place(x=210, y=240)

        quit_button = Button(root, text="Quit", command=root.quit)
        quit_button.place(x=265, y=300)

obj = setup()
obj.login()

Upvotes: 1

Kris
Kris

Reputation: 589

You could use a static method decorator.

For example:

class setup:
    @staticmethod
    def login():
        login_button = Button(root, text="Click here to enter data: ",
                              command=lambda: self.validation(username_input_box.get(), password_input_box.get()))

        login_button.place(x=210, y=240)

        quit_button = Button(root, text="Quit", command=root.quit)
        quit_button.place(x=265, y=300)

Note that I've removed the self parameter, since login wasn't using local variables. If it needs to, you may need to do this slightly differently.

Now you can call the function from outside the class without instantiating an object, like so:

setup.login()

Upvotes: 0

Related Questions