为什么我的Python类说我有2个参数而不是1个?

5 投票
9 回答
1282 浏览
提问于 2025-04-15 16:48
#! /usr/bin/env python
import os
import stat
import sys
class chkup:

        def set(file):
                filepermission = os.stat(file)
                user_read()
                user_write()
                user_exec()

        def user_read():
                """Return True if 'file' is readable by user 
            """
            # Extract the permissions bits from the file's (or
            # directory's) stat info.
                b = bool(filepermission.st_mode & stat.S_IRUSR)
                print b
            return b

        def user_write():
                """Return True if 'file' is readable by user 
            """
            # Extract the permissions bits from the file's (or
            # directory's) stat info.
                b = bool(filepermission.st_mode & stat.S_WRUSR)
                print b
            return b

        def user_exec():
                """Return True if 'file' is readable by user 
            """
            # Extract the permissions bits from the file's (or
            # directory's) stat info.
                b = bool(filepermission.st_mode & stat.S_IXUSR)
                print b
            return b

def main():
        i = chkup()
        place = '/net/home/f08/itsrsw1/ScriptingWork/quotacheck'
        i.set(place)

if __name__ == '__main__':
        main()

用这段代码我得到了

> Traceback (most recent call last):
  File "chkup.py", line 46, in <module>
    main()
  File "chkup.py", line 43, in main
    i.set(place)
TypeError: set() takes exactly 1 argument (2 given)

有什么想法吗?

9 个回答

2

你需要明确地传递一个叫做 self 的变量,它代表了一个类的实例,比如:

def set(self, file):
    filepermission = os.stat(file)
    self.user_read()
    self.user_write()
    self.user_exec()

这个变量不一定要叫 self,但遵循这个命名规则是个好习惯,这样其他程序员看你的代码时会更容易理解。

4

因为你没有把对象(通常叫做 self)作为第一个参数传递给你的方法。在Python中,像这样的调用:

my_obj.do_something(my_other_obj)

实际上是被简化成这样一个调用:

MyClass.do_something(my_obj, my_other_obj)

所以,Python在寻找一个像这样的函数定义:

class MyClass(object):
    def do_something(self, my_other_obj):
        self.my_var = my_other_obj

因此,你应该把对象(通常叫做 self)作为方法的第一个参数传递。

16

在Python类的方法中,第一个参数是self这个变量。当你调用一个方法,比如classInstance.method(parameter)时,实际上这个方法是以method(self, parameter)的方式被执行的。

所以,当你在定义你的类的时候,可以这样做:

class MyClass(Object): 
    def my_method(self, parameter): 
        print parameter

你可能还想看看这个Python教程

撰写回答