It’s possible, but it has limited usefulness: it only serves when you want to use the inner class as a "namespace", and you’ll never want to create an instance of it.
Only correct. For example, when you want to leave some parameters for the class,
but does not want to leave these parameters direct as class attributes -
to avoid confusion of names.
That is, it’s exactly what Django does in his "models": it has a lot of parameters that he needs to write down in a model class - but if everything went right under the class, no model field would be able to have the same name as none of these attributes.
For example:
In [137]:
...: class MinhaClasse:
...: a = 0
...: class Interna:
...: a = 5
...:
In [138]: obj = MinhaClasse
In [139]: obj.a
Out[139]: 0
In [140]: obj.Interna.a
Out[140]: 5
However, you should not do this if you intend to instantiate the class Interna
or if you want each instance of MinhaClasse
have a class instance Interna
. That is: for use normal class classes should not be used within classes.
If you want for example a class Veiculo
has an instance of Motor
within, the correct one is to create the two separate classes, and at the initialization of Veiculo
create the instance of Motor
to that vehicle:
In [141]: class Motor:
...: pass
...:
In [142]: class Veiculo:
...: def __init__(self):
...: self.motor = Motor()
...:
In [143]: meu_carro = Veiculo()
In [144]: meu_carro.motor
Out[144]: <__main__.Motor at 0x7f1dc57ab400>
I put this example here, because I’ve seen people think that by defining one class within another, by "magic" when you create an outside class instance, Python would create an inside class instance - that doesn’t happen.
About your last question: When should I wear
__init__
in functions within classes? / What is the difference between classes initialized with (and without)__init___
/ What good is a builder? / What’s the difference between__init__
and__new__
? / Where is the constructor of the Python class?– Woss
I would even recommend removing this doubt from the question, at least for now, to focus on the question of using class within the class. If, even after the questions mentioned, there is any doubt, you can create a new one focused on the method
__init__
. What do you think?– Woss
@Andersoncarloswoss, I withdrew the question. Thanks
– user148010