---
title: "selfless python"
author: "huangyiiiiii"
date: "2006-12-18T04:07:14Z"
tags: []
slug: "selfless-python"
draft: false
lastmod: "2006-12-18T04:07:14Z"
id: 48147
url: "https://codeplayer.iteye.com/blog/48147"
---

[Eliminating self with Metaclasses](http://www.voidspace.org.uk/python/articles/metaclasses.shtml)

此文利用 metaclass 和字节码，使得在 class 中定义方法时不再需要显式指定 self 参数，当真妙极！

关于这个 self 参数是否多余，本身也是仁者见仁、智者见智的事情。我认为 python 这么做是有它充分的理由的，那就是 class 中定义的方法本质上还是函数，是函数就应该遵循函数的规矩，没必要对方法进行特殊照顾，隐藏掉 self 参数只是增加了一份 magic。  
也许你会问了：那这个 self 是怎么传进去的呢？这里不又是一个 magic 吗？其实，这是利用了 [descriptor](http://users.rcn.com/python/download/Descriptor.htm) 对函数进行了包装，而 [descriptor](http://users.rcn.com/python/download/Descriptor.htm) 本身是个应用面很广的概念，并不只是为了实现这个而生的。

不管怎么说，相信总是有一些人(可能还是不少人)不喜欢这个 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()
> ```