python类 返回属性值_如何将函数作为类属性赋值成为Python中的方法?

你是对的,这与描述符协议有关.描述符是如何传递接收器对象,因为方法的第一个参数是在Python中实现的.您可以从

here中了解有关Python属性查找的更多详细信息.以下显示的是较低级别,当您执行A.func = func时发生的情况; A.func:

# A.func = func

A.__dict__['func'] = func # This just sets the attribute

# A.func

# The __getattribute__ method of a type object calls the __get__ method with

# None as the first parameter and the type as the second.

A.__dict__['func'].__get__(None, A) # The __get__ method of a function object

# returns an unbound method object if the

# first parameter is None.

a = A()

# a.func()

# The __getattribute__ method of object finds an attribute on the type object

# and calls the __get__ method of it with the instance as its first parameter.

a.__class__.__dict__['func'].__get__(a, a.__class__)

# This returns a bound method object that is actually just a proxy for

# inserting the object as the first parameter to the function call.

因此,在类或实例上查找函数会将其转换为方法,而不是将其分配给类属性.

classmethod和staticmethod只是略有不同的描述符,classmethod返回绑定到类型对象的绑定方法对象,而staticmethod只返回原始函数.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值