Home > other >  Ptyhon subclasses access to the parent class private properties
Ptyhon subclasses access to the parent class private properties

Time:11-22

Subclasses what also don't write, can normal visit

The code is as follows:
 
# parent
The class School (object) :
Def __init__ (self) :
Self. Money=1000
Self. __money=200000

Def __money_info (self) :
Print (f 'nest egg: [{self. __money}]')

Def print_info (self) :
Self. __money_info ()

Def get_money (self) :
Return the self. __money

# subclass
The class Students (School) :
Pass


S=Students ()
Print (s.g et_money ()) # & gt;> 200000
Supachai panitchpakdi rint_info () # & gt;> Money: [200000]


Can be defined in a subclass the __init__, error, solving
Change the code is as follows:

 
The class Students (School) :
Def __init__ (self) :
Pass


Error message: AttributeError: 'Students' object has no attribute' _School__money '

CodePudding user response:

 
# subclass
The class Students (School) :
Def __init__ (self) :
Super () __init__ ()

  • Related