简体   繁体   English

将对象传递给函数时类型错误

[英]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 .每张账单都是一个对象,具有属性startmonth (第一个月endmonth )、 endmonth (最后一个月childName )和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.我使用了 tkinter 下拉菜单来获取所需的月份并将所选月份传递给函数。 However, when i try and run this I get the error;但是,当我尝试运行它时,出现错误;

TypeError: startmonth() missing 1 required positional argument: 'bill'类型错误:startmonth() 缺少 1 个必需的位置参数:'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:我正在尝试理解您共享的代码,并且我假设startmonthcalculate_bill类的一个方法,到目前为止一切正常,但是您缺少两件事:

  1. Your function and class attributes are ambiguous, startmonth is the name of an attribute and a method.您的函数和类属性不明确, startmonth是属性方法的名称。 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.函数startmonth已经收到账单:它被称为self ,所以你不需要将bill作为参数传递。 The first argument of an instance method is always itself, and traditionally called self , although not necessarily.实例方法的第一个参数总是它自己,传统上称为self ,尽管不一定。

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.尝试使用 CamelCase 作为类名,它使它们更容易识别。
  2. set_startmonth doesn't need the bill argument. set_startmonth不需要bill参数。 it already has it, with self .它已经有了它,带有self
  3. It's perfectly normal to write methods to set instance attributes, read about "setters"编写方法来设置实例属性是完全正常的,阅读“setter”

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

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