首页 > 解决方案 > Python 错误:TypeError:patientInfo() 缺少 1 个必需的位置参数:“疾病”

问题描述

我是 Python 的新手,我正在尝试学习如何使用类。有谁知道这怎么不起作用?代码在这里:

这是我的病人课

class Patient:
    # Constructor
    def __init__(self, name, Age, Gender, Disease):
        self.name = name
        self.Age = Age
        self.Gender = Gender
        self.Disease = Disease

    # Function to create and append new patient
    def patientInfo(self, Name, Age, Gender, Disease):
        # use  ' int(input()) ' method to take input from user
        ob = Patient(Name, Age, Gender, Disease)
        ls.append(ob)

并希望patientInfo在主类中访问,但同时访问获取有关位置参数的错误。

主类的代码在这里:

                   elif user_choice == 2:
                    print()
                    f = open("myfile.txt", "a")
                    f.write(input('\n'))
                    # "{}\n".format(name)
                    name = f.write(input("Name: "+ "\n"))
                    f.write("\n")
                    Age = f.write((input("Age: "+ "\n")))
                    Gender = f.write(input("Gender: "+ "\n"))
                    Disease = f.write(input("Disease: "+ "\n"))
                    f.close()
                    Patient.patientInfo(name, Age, Gender, Disease)

你能告诉我我哪里出错了吗?

标签: pythonoop

解决方案


要使您的代码正常工作,您有 2 个选项:

  1. 如果您想在patientInfo不创建类对象的情况下调用,Patient则将函数更改如下:
     @staticmethod
     def patientInfo(Name, Age, Gender, Disease):
        # use  ' int(input()) ' method to take input from user
        ob = Patient(Name, Age, Gender, Disease)
        ls.append(ob)
  1. 如果您不想像上面那样更改函数声明:创建一个obj类的对象(例如)Patient并将其称为obj.patientInfo(...)

推荐阅读