调用python函数时出错,TypeError:returnbook()缺少1个必需的位置参数:“self”

2024-05-23 08:04:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个python程序,在该程序中,客户可以从库中归还图书和借阅图书,同时执行I get error*TypeError:borrow()缺少1个必需的位置参数:“self”*

为了成功执行程序,我应该做哪些更改

我将首先调用returnbook()函数,因为库目前没有书籍


class Library:
    def __init__(self):
        self.availablebook = availablebook
    def reducebook(self,book):
        if book in self.availablebook:
            self.availablebook.remove(book)
            print('book is removed')
    def addbook(self,book):
        self.availablebook.append(book)
        print('book added')

class Customer:
    def borrow(self):
        print('enter book')
        book = input()
        Library.reducebook(book)
    def returnbook(self):
        print('enter book')
        book = input()
        Library.addbook(book)

while True:
    print('enter 1 for add book,2 for borrow book,3 to exit')
    self.x = int(input())
    if(x==1):
        Customer.borrow()
    elif(x==2):
        Customer.returnbook()
    else:
        print('exiting')
        quit()



Tags: self程序inputdeflibrarycustomerclass图书
3条回答

创建Customer类的实例,不要直接使用该类:

customer = Customer()
customer.borrow()
customer.returnbook()

您的代码中有一些错误:

  1. self.x不是类的属性。你可以直接写x
  2. 您必须添加availablebook变量作为init函数的输入
  3. 由于没有以良好的方式创建LibraryCustomer类,因此缺少了一个参数。如果你考虑添加^ {CD3}},你可以写^ {CD6}},否则只写^ {CD8}}。<李>

我认为最好是在循环之前创建一个库:my_lib = Library([]) 然后在Customer函数中添加一个库输入,以便编辑所需的库,从而避免每次创建新库

以下是我建议您使用的代码:

class Library:
    def __init__(self, availablebook):
        self.availablebook = availablebook

    def reducebook(self, book):
        if book in self.availablebook:
            self.availablebook.remove(book)
            print('book is removed')

    def addbook(self,book):
        self.availablebook.append(book)
        print('book added')

class Customer:
    def borrow(self, library):
        print('enter book')
        book = input()
        library.reducebook(book)

    def returnbook(self, library):
        print('enter book')
        book = input()
        library.addbook(book)

my_lib = Library([])
while True:
    print('enter 1 for add book,2 for borrow book,3 to exit')
    x = int(input())

    if(x==1):
        Customer().borrow(my_lib)

    elif(x==2):
        Customer().returnbook(my_lib)

    else:
        print('exiting')
        quit()

availablebook应该是__init__函数中的列表

self.availablebook = []

另外,修改while循环

while True:
    print('enter 1 for add book,2 for borrow book,3 to exit')
    x = int(input())
    if(x==1):
        Customer().borrow()
    elif(x==2):
        Customer().returnbook()
    else:
        print('exiting')
        quit()

相关问题 更多 >

    热门问题