【问题标题】:What happens when you call object.__new__?当你调用 object.__new__ 时会发生什么?
【发布时间】:2013-10-16 22:28:52
【问题描述】:
  1. 老式类

    class Person():
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed1 is ahmed2
    print ahmed1
    print ahmed2
    
    
    >>> False
    <__main__.Person instance at 0xb74acf8c>
    <__main__.Person instance at 0xb74ac6cc>
    >>>
    
  2. 新型类

    class Person(object):
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed2 is ahmed1
    print ahmed1
    print ahmed2
    
    >>> True
    <__main__.Person object at 0xb74ac66c>
    <__main__.Person object at 0xb74ac66c>
    >>>
    

我想了解调用object.__new__时两个版本的代码会发生什么?

【问题讨论】:

    标签: python inheritance new-operator new-style-class


    【解决方案1】:

    旧式类不支持 __new__ 方法:

    >>> class Foo:
    ...     def __new__(self, *args, **kw):
    ...         print 'Nope'
    ... 
    >>> Foo()
    <__main__.Foo instance at 0x101f5c908>
    

    __new__ 只是一个新的类特性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2020-06-12
      • 2012-10-06
      • 2018-07-15
      • 2019-01-19
      • 1970-01-01
      • 2011-05-05
      相关资源
      最近更新 更多