Eliminating self with Metaclasses
此文利用 metaclass 和字节码,使得在 class 中定义方法时不再需要显式指定 self 参数,当真妙极!
关于这个 self 参数是否多余,本身也是仁者见仁、智者见智的事情。我认为 python 这么做是有它充分的理由的,那就是 class 中定义的方法本质上还是函数,是函数就应该遵循函数的规矩,没必要对方法进行特殊照顾,隐藏掉 self 参数只是增加了一份 magic。
也许你会问了:那这个 self 是怎么传进去的呢?这里不又是一个 magic 吗?其实,这是利用了
descriptor 对函数进行了包装,而
descriptor 本身是个应用面很广的概念,并不只是为了实现这个而生的。
不管怎么说,相信总是有一些人(可能还是不少人)不喜欢这个 self 参数,那让我们回到主题,看看去掉 self 参数之后的 class 定义是什么样的:
class Test(object):
__metaclass__ = Selfless
def __init__(x=None):
self.x = x
def getX():
print self.x
def setX(x):
self.x = x
test = Test()
test.getX()
test.setX(7)
test.getX()
分享到:
相关推荐
基于SUMO(STR-SUMO)的无私流量...建议使用Python 3.x,所需的软件包包含在requirements.txt中。 您可以使用pip直接安装它们(对于Python 3.x): pip3 install requirements.txt 您还需要正确安装SUMO: : 仓库的
语言:English 将“ Selfie”一词替换为“ Self Portrait” 扫描网页中是否出现“ selfie”一词,并将其替换为“ self portrait”。
将“Selfie”一词替换为“Self Portrait” 扫描网页中是否出现“ selfie”一词,并将其替换为“ self portrait”。 支持语言:English
这是一个基于B/S结构的通信原理仿真平台的源代码和技术报告还有Demo。它可以帮助你建立一个通信原理网上实验室,为学生提供在线实验。...her selfless help, I couldn’t finish the program in time
They are incredibly smart, generally selfless, and hard-working individuals who share their creations (for free) with the world. When they see a book like this, they get concerned that their site ...