首页 > Linux操作系统 > Linux操作系统 > Python中的__new__()详解


原创 Linux操作系统 作者:jieforest 时间:2012-06-13 06:37:21 0 删除 编辑
Lately I started looking into Django code and wish to write about internals of Django. I started with Django models and will be writing about it soon.

For understanding how Django models work, I had to understand what metaclasses are and how metaclasses work.

Metaclasses use method "__new__" and so I looked at what "__new__" does.

As __new__ is a static method, we will see a lttle bit about static methods and then __new__ in detail.

1. Understanding static methods.

2. Understanding method "__new__" of any class. We will see how to override method __new__ in a class.

Also, I will be trying all the code we write here on Ipython and I suggest you to try everything on Ipython as well.

Static methods

A little bit about instance methods first. Let's write a class.


In [1]: class A(object):
   ...:     def met(self, a, b):
   ...:         print a, b
   ...:In this case, met() is an instance method. So, it is expected that we pass an instance of A as the first argument to met.
Let's create an object and call met() on the created object and pass two arguments to met().


In [4]: bj = A()

In [5]: obj.met(1,2)
1 2                #output

来自 “ ITPUB博客 ” ,链接:,如需转载,请注明出处,否则将追究法律责任。

下一篇: PHP表单处理指南
请登录后发表评论 登录


  • 博文量
  • 访问量