Someone please translate the following sentence into ENGLISH for me?
“The init method — also called a constructor — is a special method that runs when an instance is created so we can perform any tasks to set up the instance.”
It sounds like: ‘it’s a special thing that runs when a thing is created so we can do anything to set up the thing.’
__init__(self) is not compulsary, it’s a convenience. So things are done to and by the object when people do
var = model() at moment of instantiation. There are also scenarios where information is not available at class instantiation time, but only at data fitting time, so we can only pass in parameters using
transformer.fit() and not during
trans = transformer() (eg. when writing sklearn custom transformers)
Inside init we can define a ton of
self.any_name_but_usually_attribute = attribute. Inside init itself you can refer to either the left hand side or right hand side of = name. Outside init in other methods of class they will only have access to
Besides assigning those simple attributes you can also make calls to functions (can even call own methods of class), like
result = self.get_file(). If you think why that works when the methods are coded beneath the init method and python runs top down so shouldn’t have seen those methods, thats because before you instantiate the class, you must have already ran through the class definition, so python knows all about that class’s contents.
Almost all python objects have
obj.__dict__, which is a dictionary attached to an object that describes it and can be manipulated. You can think of programming as just attaching attributes representing real life concepts to objects, and writing processing code to manipulate those attributes.
__init__ is a way of setting up this
obj.__dict__.This idea of “referencing another part of memory” (commonly seen as dictionary/list indexing) can help you understand complex python in future.
Here are 2 interesting ways to confuse yourself
- Peculiar Self-References - Susam Pal