简体   繁体   中英

Type Error when passing an object into a function

For a school project I am creating a billing system for a local nursery. Each bill is an object with the attributes startmonth (the first month to bill from), endmonth (the last month to bill to) and childName .

class calculate_bill:
    def __init__(self, startmonth, endmonth, childName):
        self.startmonth = startmonth
        self.endmonth = endmonth
        self.childName = childName`

I have used a tkinter dropdown to get the desired months and pass the selected month into a function. However, when i try and run this I get the error;

TypeError: startmonth() missing 1 required positional argument: 'bill'

Not sure what this means or how to solve it. Any advice would be greatly appreciated

def startmonth(self, m1, bill):
    bill.startmonth = m1
    print(bill.startmonth)

I'm trying to make sense of the code you shared, and I assume that startmonth is a method of the calculate_bill class, everything OK so far, but you're missing two things:

  1. Your function and class attributes are ambiguous, startmonth is the name of an attribute and a method. Change one of the two to something else.

  2. The function startmonth already receives the bill: it's called self , so you don't need to pass bill as an argument. The first argument of an instance method is always itself, and traditionally called self , although not necessarily.

This is a more valid representation of what are you trying to do:

class CalculateBill:
    def __init__(self, startmonth, endmonth, childName):
        self.startmonth = startmonth
        self.endmonth = endmonth
        self.childName = childName`

    def set_startmonth(self, m1):
        self.startmonth = m1
        print(self.startmonth)

Some pointers about this code:

  1. Try to use CamelCase for class names, it makes them more easy to identify.
  2. set_startmonth doesn't need the bill argument. it already has it, with self .
  3. It's perfectly normal to write methods to set instance attributes, read about "setters"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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