why defined '__new__' and '__init__' all in a class

前端 未结 4 822
轻奢々
轻奢々 2020-12-24 03:39

i think you can defined either \'__init__\' or \'__new__\' in a class,but why all defined in django.utils.datastructures.py.

my code:

4条回答
  •  鱼传尺愫
    2020-12-24 04:13

    In my opinion, there was no need of overriding __new__ in the example you described. Creation of an instance and actual memory allocation happens in __new__, __init__ is called after __new__ and is meant for initialization of instance serving the job of constructor in classical OOP terms. So, if all you want to do is initialize variables, then you should go for overriding __init__. The real role of __new__ comes into place when you are using Metaclasses. There if you want to do something like changing attributes or adding attributes, that must happen before the creation of class, you should go for overriding __new__.

    Consider, a completely hypothetical case where you want to make some attributes of class private, even though they are not defined so (I'm not saying one should ever do that).

    class PrivateMetaClass(type):
          def __new__(metaclass, classname, bases, attrs):
              private_attributes = ['name', 'age']
    
              for private_attribute in private_attributes:
                  if attrs.get(private_attribute):
                     attrs['_' + private_attribute] = attrs[private_attribute]
                     attrs.pop(private_attribute)
    
              return super(PrivateMetaClass, metaclass).__new__(metaclass, classname, bases, attrs)
    
    
    class Person(object):
    
          __metaclass__ = PrivateMetaClass
    
          name = 'Someone'
          age = 19
    
    person = Person()
    >>> hasattr(person, 'name')
    False
    >>> person._name
    'Someone'
    

    Again, It's just for instructional purposes I'm not suggesting one should do anything like this.

提交回复
热议问题