+ 2
Is it this correct way to inherit?
I only want b and c parameters to be inherited. https://code.sololearn.com/clwmkIOJwhEO/?ref=app
13 odpowiedzi
+ 3
You don't have default values in your class X. So you need all required arguments.
But to answer your questions.
No in Python we have something called Data hiding like this. If you don't use it you have access to a, b, c, d with the self keyword.
https://www.sololearn.com/learn/Python/2471/?ref=app
+ 3
This could also help you to understand this topics better.
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2484/?ref=app
https://www.sololearn.com/learn/Python/2469/?ref=app
+ 3
It's both okay but it's like I said. That you have access to them if you don't write it like that.
If you write
self.a = a
Then you could write in you Y class
print(self.a)
If you write
self.__a = a
Then you can't write
print(self.a) # error
Read the links I posted and try by yourself and you will see what happens.
+ 2
Lenoname
Inheritance is messy and should be avoided.
As Ashkan Sh 🇺🇦🇺🇦🇺🇦 pointed out, you also have to handle unused properties. Is it worth the trouble?
But if you must, you can define multiple constructors in your base class.
https://code.sololearn.com/cQA6713W4HlT/?ref=app
+ 1
Hi.
There are few problems here.
The main issue: Super().method() means execution of super class. It is equal to X().__init__ in your case.
As X().__init__ needs 4 attribute, you can't go for 2 because Y(X) needs 2. (Causes an error)
Also using the same method of superclass with different number of attributes in subclass cause confusion. It can work, but it wastes the inheritance effect.
Check this out:
https://code.sololearn.com/cbxJKJcCx3uj/?ref=app
+ 1
The real inheritance is like this:
https://code.sololearn.com/c7fJm3vmn3m4/?ref=app
I believe when a subclass inherits from a superclass, it uses all parameters.
So I think Stefanoo meant, if you need only b and c, you can hide a and d.
Hope it helped.
0
I dont really understand data hiding, so u want me to give a,b,c,d = None values for example?
0
No you just write for example
self.__a = a
instead of
self.a = a
0
class X :
def __init__(self, __a, __b, __c, __d):
self.__a = a
self.__b = b
self.__c = c
self.__d = d
class Y(X) :
def __init__(self, b, c):
super().__init__(b, c)
??
0
If you call super init you have to pass all arguments with no default values.
Like this
super().__init__(1, b, c, 4)
https://code.sololearn.com/cJ7Av0CwVCP7/?ref=app
0
So if u dont write self.__a = a in your code u will get an error?
0
I mean if u write self.a = a instead for example