Python中的__new__()詳解

jieforest發表於2012-06-13
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.

CODE:

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().

CODE:

In [4]: bj = A()

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

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-732625/,如需轉載,請註明出處,否則將追究法律責任。

相關文章