I was trying to change the discount rate of a particular sub class, while the default is set at 0, and in subclass it changes to 5, however, this is not refelected.
I cannot switch the discount scheme on Class B, because all class need to have access on it.
class A:
def __init__(self, x, y, discount=0):
self.discount=0
if self.discount>0:
discount = self.discount
else:
discount=0
self.discount=discount
self.x=x
self.y=y
self.discount=discount
discount=5
class B(A):
def __init__ (self,x,y,z):
super().__init__(x,y)
B.z=z
B.discount=5
class C(A):
def __init__ (self,x,y,a):
super().__init__(x,y)
C.a=a
C.discount = 10
a = y*10
one=A(1,2)
print(one.x)
print(one.discount)
two = B(1,2,3)
print(two.x)
print(two.z)
print(two.discount)
three = C(4,5,6)
print(three.x)
print(three.discount)
Output:
1
0
1
3
0
4
0
Tried to do some calculations and integrate methods, but it only works for methoid but not on the class, as you can see, the discount is set to 0 and doesn't change.
CodePudding user response:
The constructor of your A
class seems quite confusing. If the only thing you need is to check if the discount
parameter is greater than 0
and set it to your instance's discount
variable, you can simplify your code like this:
class A:
def __init__(self, x, y, discount=0):
self.discount=0
if discount>0:
self.discount = discount
self.x=x
self.y=y
Moreover, when you try to modify an instance variable in a subclass, you can still use self
:
class B(A):
def __init__ (self,x,y,z):
super().__init__(x,y)
self.z=z
self.discount=5
class C(A):
def __init__ (self,x,y,a):
super().__init__(x,y)
self.a=a
self.discount = 10
a = y*10
Running the commands again, you 'll get:
1
0
1
3
5
4
10
You can find more about instance and class variables here and inheritance here.