+ 1

Python nested class and also a main class itself?

Hi! Supposing we have the class Person. Inside Person is another inner (nested) class named Dog. Dog object cannot exist without a Person object. Is there any way to have a Dog class and can access it as we access Person class but without creating another class Dog outside Person class? Else, if not possible, how to do it better to avoid confusion and to have Dog object with all it's methods and also a Person object with it's dog object with it's features? There isn't any way to avoid having both Dog class as inner class and also as an outside class of Person? There is to much code write and want to avoid this. Thank you so much!

15th Aug 2019, 1:28 PM
Constantin Ghineț
Constantin Ghineț - avatar
6 Answers
+ 1
You can define the Dog class as __Dog, then it's not strictly available from outside from the class, but you can access it from the methods of Person.
15th Aug 2019, 2:23 PM
Seb TheS
Seb TheS - avatar
+ 1
What if I need to create an object of class Dog by itself, as the main class, like Person is?
16th Aug 2019, 5:22 AM
Constantin Ghineț
Constantin Ghineț - avatar
+ 1
Then you can use: _Person__Dog to access the __Dog class. dog = _Person__Dog()
16th Aug 2019, 5:26 AM
Seb TheS
Seb TheS - avatar
+ 1
How to make a class hidden like that by itself, outside of any class, e.g. class __MyClass: And then how to create objects from it? Also, how to inherit it by other classes? Thank you so much!
16th Aug 2019, 9:54 AM
Constantin Ghineț
Constantin Ghineț - avatar
+ 1
Any way to do it?
16th Aug 2019, 11:17 AM
Constantin Ghineț
Constantin Ghineț - avatar
+ 1
"Also, how to inherit it by othee classes?": Names, that start with 2* "_", (except magic methods) will not be automatically inherited by other classes: class A: __a = 5 class B(A): pass #__a will not be inherited. #But you can inherit it manually: class C(A): __a = _A__a "How to make a class hidden like that by itself, outside of any class, e.g. class __MyClass:": If you define private names outside a class, they will lose their private meanings, and can be used everywhere, except from outside the file. "And how to create objects from it?": You can easily create objects of it, my_cls_obj = __MyClass()
16th Aug 2019, 2:59 PM
Seb TheS
Seb TheS - avatar