I tried to return a value in a class constructor (init):
class A:
def __init__(self):
return 1
but there is a run-time error saying init should return None. If this is the case, how to understand:
a=A()
where “a” is assigned as the class instance?
Strictly speaking, it’s not
A.__new__()that’s creating the the instancea.When you define
class A(object):(orclass A:as well if you are using Python3,class A:is the old-style class that has been deprecated), it is__new__from the inheritedobject.__new__()that is being called to create the instancea.When
a = A()is executed, what happens is:A()is a shorthand forA.__call__object.__new__(cls, *args, **kwargs)wherecls=A, is what actually happens under hood to create instancea. It allocates the memory for the new object, and should then return a new object (the instance).__init__(self)then get called with the newly created object passed to it to “initilize” the object.Consider the following demo:
when we override
__new__and no longer returns an object,__init__willnot get called:
now, return a new instance by using
object.__new__, and you will see thatafter
__new__,__init__would be called as well:Here is another demo to display the difference, note that instance
acan be created without calling__init__():Now for the inquisitive (and also to refresh my own memory =]):
Roughly speaking, there are two main ways to create new objects in Python:
Create new object (type / class) by subclassing:
classstatements tells Python to create a new type / class object(bysubclassing an existing type/class such as
object):In fact all class/type object have type
type. The type oftype(
type(type)) is still type.You can subclass a type / class object.
Create new object (instance) by instantiating:
You can also create a new object by instatiating an existing type object.
This is done via the using the
__call__operator (shorthand by()):You cannot subclass an instance object.
(note that you can also create a new instance object by some other means such
as using the list operator
[1,2,3], in this case it creates an list instance)You can check an object’s type by
type(my_obj)ormy_object.__class__.Now you know how an instance object is created, but what really creates the type / class object (that allows to create instance objects)?
In fact, these objects are created by instantiation as well, albeit it is a
slightly different kind of instantiation from what was mentioned earlier.
Aside from
classstatement, you can also usetype(cls_name, parent_class_tuple, attr_dict)to create a new class.For eg:
will create the
Helloclass same as the one shown earlier.What is
type? Enter metaclass.typeis a metaclass, which is the class of class, i.e., classes areinstances of metaclasses. The
__class__oftypeis stilltype.So here is a graph that shows the relationships between metaclass, class,
instance:
When metaclass
typeis called to create a new class, the similar flow goes:type.__call__()is excutedtype.__new__()allocates memory and then returns new a class (a metaclass instace), and then callstype.__init__().type.__init__()initalizes the newly created class that was passed from step 2.You can even create a new metaclass by subclassing
type:then you can create a new class from this
MyMetametaclass just like you dowith
type:Or, use
__metaclass__when defining your class, which has exactly thesame effect as what was shown above: