B
In Python, what is an object?In Python all are objects, even native data types are objects. These accounts with attributes and methods implemented. When an object is being generated through the instance of a class, you can say that a type of custom data is being defined.This object has predefined behavior, with the definition of its attributes and methods that make use of its attributes. This, like all the elements of the program, requires space in memory.The difference between native data types and this type of custom data is that the first have a formal representation in language.A defined object does not have the official representation of a valid expression of Python.What makes an object have this formal representation?Let's see two magic methods, which can be defined in the definition of a class: https://docs.python.org/3.8/reference/datamodel.html#objects-values-and-types According to his reference in the documentation:Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.This method differs from object.rep() in that there is no expectation that str() return a valid Python expression: a more convenient or concise representation can be usedTranslating the second paragraph:This method is different from __repr__()because the method is not expected __str__ return a valid expression on Python.This means thatThe method is called when the object is used as an argument in the functions format(),print() and str().Defines an informal representation to represent the value of the object as stringThis can be verified by defining __str__() in a class:class Clase:
def __init__(self,atributo):
self.atributo = atributo
def __str__(self):
return "Objeto con el atributo {}".format(self.atributo)
If used try to make a string conversion with an object generated by this class, either print(), format() or str(). This conversion will result in the return value str().Objeto = Clase("foo")
print("Valor del objeto:",Objeto)
I would showValor del objeto: Objeto con el atributo foo
Why is it said that this is an informal representation?Because this representation is only valid at the time to perform a string cover. If you try to represent otherwise you would get that "memory address", which is actually the prredetermined description.lista_de_objetos = [Objeto]
print(lista_de_objetos)
I would show[<main.Clase object at 0x000001FC65AE60D0>]
The method str() does not define the formal representation of an object. https://docs.python.org/3.8/reference/datamodel.html#objects-values-and-types According to his reference in the documentation:Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines rep(but not) str(), then rep() is also used when an “informal” string representation of instances of that class is required.Translating a fragment of the first paragraph:It's called the function. repr() to define the "official" representation of an object. If possible, you should look like a valid expression of Python.Translating a fragment of the second paragraph:If not possible, it will be represented with a string in the form <... información útil ...>What does the function repr()?Returns the formal representation of an object in string format, when it is said object is spoken of variables, values returned by functions, etc...variable = "Mango"
print(repr(variable))
show'Mango'
Now, if the method is defined repr() in a class, you can define what this output will be.class Clase:
def init(self,atributo):
self.atributo = atributo
def __repr__(self):
return "Soy un {}".format(self.atributo)
Following the indications of the specification in the documentation:The return value must be a string object.Now the object is not only represented when using as a string:objeto_mango = Clase("Mango")
print(objeto_mango)
I'd show:Soy un Mango
Any representation is valid:lista_objetos = [objeto_mango]
print(lista_objetos)
I'd show:[Soy un Mango]
This is what is considered as a formal representation.Why when I try to print a variable your address is printed in memory and not its value?It is because when you try to print the list containing the object, this object does not have a formal representation if not with the default representation or "memory address".Why is recursion not valid in different areas within a class method?When I run the code prints the location of the objectThere's another mistake in your code.Let's see the expressionlist.append(Objeto)
This means adding to a list within the object itself.Objeto => contiene => |list_ = [Objeto]|
Note:♪ Here you change the name of list for list_because list It is a reserved word of language and this can generate problems.Objeto => contiene => |list_ = [Objeto]|
An object is being invoked as part of the same object, this would be valid if it were to be done in the.Because a new object is not being defined that forms part of another object of the same class, if not the same object is defined with an object.You cannot define something with something, since something is not defined.What is the right way to instance objects within another object with the same class?Generating an object newself.list_.append(Usuarios(self.nombre,self.genero,self.edad))
ExplanationWhen creating an object like thisusuario1 = Usuarios("Juan", "Masculino", "30")
Parameters pass to init()and they go on as class attributes. This allows the methods of such class to have native access to these parameters. By generating a new object with the attributes of the class, an object is being generated with the same parameters that the class began.objeto = Clase(arg0, arg1) #Objeto inicial
^ ^
| |
* *
init(self,arg0,arg1)
^ ^
| |
* *
funcion() => Clase(arg0,arg1) #Objeto nuevo
The initial object can store another object different from this same.Speaking of areas, it is necessary to list_ as a class attribute. In this way it has an implicit global scope on all the methods of this same class, and lasting value in the object that is initializedself.list_ = []
Represented the object formally and seeing the listso I don't know if I'm adding any information to the listBy defining the representation of the object, we can visualize this object and see if information is being added to list_def repr(self):
return "Objeto: ({}, {}, {})".format(self.nombre,self.genero,self.edad)
Invoking the class method funcion() and print the current value of the generated objectusuario1 = Usuarios("Juan", "Masculino", "30")
usuario1.funcion()
print(usuario1)
We can see that yes, The object is on the list!Masculino
[Objeto: (Juan, Masculino, 30)]
Objeto: (Juan, Masculino, 30)
I hope everything is clear to you.