python元类的一些新认识

如果定义了一个类A和他的元类B,如果只实例化B,那么A也会被实例化。
代码如下:

#coding:utf-8
class FA(type):
    def __new__(cls, name, base, attr):
        print name
        print base
        print attr
        print “it is in fa’s new”
        new_obj = super(FA, cls).__new__(cls, name, base, attr)
        return new_obj



class FB(object):
    def __init__(self):
        print “it is in FB’s init”
        self.group = ‘china’

class FC(FB):
    __metaclass__ = FA
    def __init__(self):
        print “it is in FC’s init”
        self.number = 3
        
     
#fc = FC()
print “=” * 20
fa = FA(’fa_name’, (), {’age’:22})
运行结果如下:
C:\>python test.py
FC
(<class ‘__main__.FB’>,)
{’__module__’: ‘__main__’, ‘__metaclass__’: <class ‘__main__.FA’>, ‘__init__’: <
function __init__ at 0×00B712B0>}
it is in fa’s new
====================
fa_name
()
{’age’: 22}
it is in fa’s new
有趣的是如果把fc = FC()这句前面的注释删掉,运行结果也会和上面的一样,这里我也不知道为什么会这样,也不明白为什么实例化FC对象的部分会在打印=之前出现。
如果将FB和FC类都注释起来,即只有元类,而没有他的子类,则运行结果:
====================
fa_name
()
{’age’: 22}
it is in fa’s new

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. django中ModelBase的属性
  2. Python线程编程的两种方式
  3. python3.0与2.x之间的区别

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu