绑定方法和函数之间有什么区别?

2024-04-27 21:00:02 发布

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

考虑以下类:

class Employee:
    def __init__(self,first,last,pay):
        self.first=first;self.last=last
        self.pay=pay
        self.email=first.lower()+'.'+last.lower()+"@company.com"

    def fullname(self): return "{} {}".format(self.first, self.last)

如果我像这样访问fullname方法:

em1.fullname #assume em1 object already exists

我得到以下输出:

<bound method Employee.fullname of <__main__.Employee object at 0x7ff7883acc88>>`

但是,如果我像这样访问fullname方法:

Employee.fullname

我得到以下输出:<function Employee.fullname at 0x7ff7883c9268>

为什么同一个函数/方法有两种不同的定义?我仍然在访问内存中相同的方法/函数对象,对吗


Tags: 方法函数selfobjectinitdefemployeelower
3条回答

您可以访问相同的功能

但是,为了调用函数,使用em1.fullname,您只需要:

em1.fullname()

但是对于Employee.fullname,您需要提供self参数,并且需要:

Employee.fullname(em1)

当您通过实例em1.fullname访问fullname时,会得到一个绑定方法,这意味着fullname的一个版本会自动将em1作为其第一个参数

因此,您可以调用em1.fullname(),而无需传递任何显式参数。但是如果调用Employee.fullname(),由于缺少参数self,您将得到一个错误

即使方法调用与属性访问分离,这也适用:

bound = em1.fullname
unbound = Employee.fullname

bound()       # OK, first argument is em1
unbound()     # Error, no argument for self
unbound(em1)  # OK, first argument supplied

I'm still accessing the same method/function object in memory, right?

最肯定的是,这在您提供的输出中很明显。第一个位于0x7ff7883acc88,而第二个位于0x7ff7883c9268

第一个属于实例,而第二个属于Employee类本身

相关问题 更多 >