Skip to main content
 首页 » 编程设计

python之是否可以在不定义类的情况下编写一个以 "self"作为参数的函数

2025年05月04日16lovecherry

我正在尝试通过实现函数来减少一些代码行。我正在研究将自己作为参数的函数,例如 oop。例如:

def drop_columns(self, columns): 
    return self.drop(columns, axis = 1) 
 
df.drop_columns(['id', 'date']) 

或

def print_shape(self): 
    print(self.shape) 
 
df.print_shape() 

但当然更复杂。但是,代码不起作用。如果我给它一个数据框,它会抛出一个错误: AttributeError: 'DataFrame' 对象没有属性 'print_shape'

有没有办法让它工作?

请您参考如下方法:

当您在类的实例上调用方法时,该实例将自身作为第一个参数传递。为了方便起见,我们通常称该参数为 self。

这仅在方法首先绑定(bind)到实例时有效。当您执行 df.print_shape() 时,它不起作用,因为您从未以任何方式将 print_shape() 附加到 df。

不过,以下两种方法都有效:

# approach 1: call it as a function 
print_shape(df) 
 
# approach 2: assign the function as an attribute of df, then call it as a method 
setattr(df, 'print_shape', print_shape) 
df.print_shape() 

方法 1 是首选,因为通常更好的做法是不要修改不是您自己创建的对象(并且不要像这样动态地这样做)。但是知道方法 2 的存在可以让我们对 python 作为一种语言的工作方式有一些看法/见解。如果您坐在 print_shape() 中,看不到外面发生的任何事情,您将无法分辨这两种方法之间的区别。