viernes, 23 de marzo de 2018

Python : Una excelente explicacion sobre self

https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self
 
Pongo aqui este excelente explicacion sobre el parámetro de python "self". 
El original esta en el enlace de arriba, pero copio el articulo por si es que
desapareciera, ya que esta demasiado bueno como para permiterse perderlo:
 
 
When objects are instantiated, the object itself is passed into the self parameter.
enter image description here
Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.
enter image description here
The Object is passed into the self parameter so that the object can keep hold of its own data.
Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as a general template and would not be referenced to (belong to) the object. So by passing the object's name into the self parameter it means that if 100 objects are instantiated from the one class, they can all keep track of their own data and methods.
See the illustration below:
enter image description here

escribir una lista en un archivo:
 
archivo.write("\n".join(itemlist))

No hay comentarios:

Publicar un comentario