_ _new_ _
- __new__ is for creating objects.
- Use __new__ when you need to control the creation of a new instance.
- __new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class.
- __new__ is static, class method .
- __new__ takes cls as parameter.
- __new__ is good for immutable object as they cannot be changed once they are assigned. So we can return new instance which has new state.
class A:
def __new__(cls):
print "A.__new__ is called" # -> this is never called
A( )
_ _init_ _
- __init__ is for initializing objects.
- Use __init__ when you need to control initialization of a new instance.
- In contrast, __init__ doesn't return anything,it's only responsible for initializing the instance after it's been created.
- __init__ is instance method.
- __init__ takes self as parameter.
- __init__ called on it automatically.
class A:
def __init__(self):
print "A.__init__ called"
A( )
class A:
def __init__(self):
return 29
A( )
class A(object): # -> don't forget the object specified as base
def __new__(cls):
print "A.__new__ called"
return super(A, cls).__new__(cls)
def __init__(self):
print "A.__init__ called"
A( )
Example:
def __init__(self):
print "A.__init__ called"
A( )
class A:
def __init__(self):
return 29
A( )
class A(object): # -> don't forget the object specified as base
def __new__(cls):
print "A.__new__ called"
return super(A, cls).__new__(cls)
def __init__(self):
print "A.__init__ called"
A( )
Example:
class ExampleClass(object):
def __new__(cls, value):
print"Creating new instance..."
#Call the superclass constructor to create the instance.
instance = super(ExampleClass, cls).__new__(cls)
return instance
def __init__(self, value):
print"Initialising instance..."
self.x= value
exampleInstance = ExampleClass(42)
print(exampleInstance.x)
No comments:
Post a Comment