关于self参数的问题

0 投票
2 回答
2754 浏览
提问于 2025-04-18 04:01

我正在做一个小项目,但不太确定我遇到的错误是因为我使用的IDLE有问题,还是我自己做错了什么。

我在Windows 8的电脑上使用Wing IDLE运行Python的面向对象编程(OOP),并且安装了最新版本的Python。

在我的程序中,有一个方法是用来获取用户输入的,然后根据这个输入创建一个架子所需的参数。

'def subject_creator(self): 
    subject_name = input("Enter the subject name:") 
    subject_file = subject_name + "file"  
    name = subject_name 
    return subject_name, subject_file, name' 

理想情况下,程序会使用返回的三个值:subject_name、subject_file和name,来打开新的架子。

 'def __init__(self, subject_name,  subject_file, name ): 
    subject_name = shelve.open ("subject_file", "c") 
    self.name = name  
    print("The", self.name ,"note has been created")' 

 while True:
    print ("""
    1.Create new note
    2.Add new term 
    3.Look up term 
    4.Exit/Quit
    """)
    ans=  input("What would you like to do?: ") 
    if ans=="1":  
            subject_creator() 
            note = Notebook(subject_name, subject_file, name) 
            subject_name.sync() 

但是,当我运行程序并在主菜单中选择选项1来执行上面的代码时,我收到了一个错误提示。

<module>
builtins.TypeError: subject_creator() missing 1 required positional argument: 'self' 

这让我有点困惑,因为在我为主题创建器编写代码时,确实包含了self参数。除此之外,我没有其他错误。

任何反馈都将非常感激。

2 个回答

0

这一行代码导致了你的错误

subject_creator()

你应该把它改成

def subject_creator(self): 
    subject_name = input("Enter the subject name:") 
    subject_file = subject_name + "file"  
    name = subject_name 
    return subject_name, subject_file, name

改成这个

def subject_creator(): 
    subject_name = raw_input("Enter the subject name:") 
    subject_file = subject_name + "file"  
    name = subject_name 
    return subject_name, subject_file, name

如果你在函数中不打算使用某个参数,那就不需要把它写进去。

另外,如果你在用的是 Python 2.x 版本,建议使用 raw_input() 而不是 input()。想了解更多,可以看看 input() 和 raw_input() 的区别

2

你把“函数”和“方法”搞混了。

在Python中,方法是定义在一个class类里的函数,它会自动把对象作为第一个参数传入(这个参数通常不需要显式写出来):

class Example:
    def try_me(self):
        print "hello."

你可以这样使用它:

x = Example()
x.try_me()

这里,try_me()会把x作为第一个参数(在这里被忽略)传入。这很有用,因为这样方法可以访问对象实例的属性等等。

把这个和普通函数对比一下,普通函数就是在class外面定义的:

def try_me_too():
    print "hello."

普通函数的调用方式很简单:

try_me_too()

顺便提一下,你的示例代码没有获取到subject_creator函数返回的值:

>    if ans=="1":  
>        subject_creator() 
>        note = Notebook(subject_name, subject_file, name)

发生这种情况的范围内没有名为subject_name等的变量。你需要以某种方式创建它们。

if ans=="1":
    ick, bar, poo = subject_creator()
    note = Notebook(ick, bar, poo)

(我选择这些无意义的变量名主要是为了强调它们和在subject_creator内部定义的变量不同,后者只能在内部使用。)


为了补充说明,这里有一个self如何有用的示例。

class Otherexample:
    def __init__(self, greeting):
        self.greeting = greeting
    def try_me_also(self):
        print self.greeting

用法如下:

y = Otherexample("hello.")
y.try_me_also()

在这里,问候语是我们创建的对象的一个属性;__init__方法把它作为参数接收,并将其存储为实例的一个属性。try_me_also方法使用self来获取这个属性并打印出来。

撰写回答