2.
>>> print str('a') a >>> print str.__init__('a') None >>> print str.__call__('a') a
3.
MyClass(a, b) = 1
>>> print str('a') a >>> print str.__init__('a') None >>> print str.__call__('a') a
MyClass(a, b) = 1
As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.3. Думаю нет. Результатом же будет ссылка на экземпляр или immutable, для которого вообще бессмысленно.
Вызывается hz.__call__(1)
Если hz — класс, то __call__ создает его экземпляр вызывая __new__ и __init__
odnochlenКак я понимаю: классы создает type, внутри его __call__ все и вызывается.
А как он вызывает __new__ и __init__?
. Вот что будет если переопределить type и добавить принты:class FooMeta(type): def __call__(mcs, *args, **kwargs): print 'mcs call', args, kwargs return super(FooMeta, mcs).__call__(*args, **kwargs) def __new__(mcs, name, bases, attrs): print 'mcs new', name, bases, attrs return super(FooMeta, mcs).__new__(mcs, name, bases, attrs) def __init__(mcs, *args, **kwargs): print 'mcs init', args, kwargs return super(FooMeta, mcs).__init__(*args, **kwargs) class Foo(object): __metaclass__ = FooMeta def __new__(cls, *args): print 'ex new', cls, args return super(Foo, cls).__new__(cls, *args) def __init__(self, *args): print 'ex init', args foo = Foo(123) foo = Foo(321)
mcs new Foo (<type 'object'>,) {'__module__': '__main__', '__metaclass__': <class '__main__.FooMeta'>, '__new__': <function __new__ at 0x015751F0>, '__init__': <function __init__ at 0x01575230>}
mcs init ('Foo', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.FooMeta'>, '__new__': <function __new__ at 0x015751F0>, '__init__': <function __init__ at 0x01575230>}) {}
mcs call (123,) {}
ex new <class '__main__.Foo'> (123,)
ex init (123,)
mcs call (321,) {}
ex new <class '__main__.Foo'> (321,)
ex init (321,)odnochlenЕсли базовые методы не вызывать то да. Но для своих модификаций immutable типов или при реализации штук наподобие декларативного Django ORM, Enthought Traits и т.п., без этого не обойтись.
Т.е. переопределение __new__ и __call__ в классах ничем хорошим не закончится?