Search code examples
python-3.xooppython-class

[Beginner Python]Issues trying to access a function within a class


I am trying to run a simple budget program and I am a complete beginner with classes in python. I am trying to run everything within the class so I can call back to specific functions. The problem is I can't get the functions to work, I keep returning a NameError when I try to run any function. It keeps saying "billNamePrompt() isn't defined" despite being defined?

bill_name = ''
...
class Prompts:
    def __init__(self, bill_name):
        print("Hello! Welcome to my mini-budgeting program")
        billNamePrompt()

    def billNamePrompt(self):
        self.bill_name = input("Please input the name of the bill: ")
        return self.bill_name

...


Prompts(bill_name)

I have tried messing around with it a little, but I have such little experience with Classes that I have no real idea of what I am doing. What am I doing wrong for it to not execute within the class? I thought classes were capable of running functions within classes? Sorry if the solution is super obvious, but I cannot find an answer anywhere.


Solution

  • __init__ means the first function when you call the class. So in your code, you are calling the function before defining it.

    Your code running like this:

    Prompts -> __init__ -> calling billNamePrompt() -> identifying billNamePrompt()

    You can solve the problem by adding self. Or you can just write your code into __init__ without adding another def.