如何使用类和继承更改python中的默认折扣?



我试图改变一个特定子类的贴现率,而默认设置为0,并且在子类中它更改为5,但是,这没有反映出来。

我不能在类B上切换折扣方案,因为所有类都需要访问它。

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)

输出:

1
0
1
3
0
4
0

尝试做一些计算和集成方法,但它只适用于methoid而不适用于类,如您所见,折扣被设置为0并且不改变。

您的A类的构造函数似乎相当令人困惑。如果您只需要检查discount参数是否大于0并将其设置为实例的discount变量,则可以这样简化代码:

class A:
def __init__(self, x, y, discount=0):
self.discount=0
if discount>0:
self.discount = discount
self.x=x
self.y=y

此外,当您尝试修改子类中的实例变量时,您仍然可以使用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

再次运行命令,您将得到:

1
0
1
3
5
4
10

你可以在这里找到关于实例和类变量的更多信息,在这里找到继承。

最新更新