I was looking at some Js tutorials on objects, not on OOP and I saw that objects could be placed inside objects, I attach the js code:
const persona= {
nombre: "pepito",
contacto:{
telefono: {
movistar:{
fijo: 6465465,
movil:65464654
},
claro: 65464654
},
email: "[email protected]"
},
}
print("El telefono movistar fijo es: "+str(persona.contacto.telefono.movistar.fijo))
// Ejecución exitosa
>> El telefono movistar fijo es: 6465465
What would be the equivalent in in python?
I was looking for information, but the only thing I find is about OOP, the code I have is like this:
class Config:
def __init__(self):
self.nameExe = "software.exe"
self.debugger = False
self.other = "other"
def accion1(self):
print("se realizó la acción")
My question is if it is possible or simply python does not work like that
If you have a forum or a link where I can see it I would greatly appreciate it.
Yes of course you can in Python. Here is an explained example of two classes RandomNumber that generates a random number, and GenerateRandomList that generates a list of random numbers, using RandomNumber :
Speaking from my personal experience, I only usually initialize objects within objects when:
If I don't usually solve problems like the one I have given you above, through class inheritance.
In summary
If all this has seemed complicated or a bummer. The answer is yes. And the best way to remember that you can create objects within objects is that anyone who creates an object in Python is almost certainly using objects without their knowledge.
When you use the symbols
==
you are actually creating that object inside the class by calling the class__eq__
which in Python is a special method. Same with>
what it is__gt__
. Also when you create strings, the strings really are objects!! You can check this withisinstance("hola qué tal?", str)
Objects within objects in Python
We can access values and functions inside objects