如果在使用getter和setter时声明?

时间:2019-05-10 21:18:30

标签: python oop polymorphism

我试图根据“ macType”返回计算机的价格,“ macType”是计算机的大小。我不知道在哪里将if语句集成到我的代码中,啊!!!

class apple:
    def __init__(self,pType,price):
        self.__pType=pType
        self.__price=price

    def setpType(self,pType):
            self.__pType=pType

    def setprice(self,price):
            self.__price=price

    def getpType(self):
        return self.__pType

    def getprice(self):
        return self.__price

class mac(apple):
    def __init__(self,pType,price,macType):
        apple.__init__(self,pType,price)
        self.__price=price
        self.__macType=macType

    def setmacType(self,macType):
            self.__macType=macType

    def setmacPrice(self,price):
        if(macType()=="11Inch"):
            self.__price=float(price*.9)
        elif(macType()=="13Inch"):
            self.__price=price
        elif(macType()=="15Inch"):
            self.__price=float(price*1.2)

    def getmacType(self):
        return self.__macType

    def getprice(self):
        if (self.__macType == "11inch"):
            return super(mac, self).getprice()*.9
        elif (self.__macType == "13inch"):
            return super(mac, self).getprice()
        else:
            return super(mac, self).getprice()*1.1

a1 = apple("computer",1000)
m1 = mac("computer",1000,"11Inch")
m2 = mac("computer",1000,"13Inch")
m3 = mac("computer",1000,"15Inch")

print("a1 is a ",a1.getpType(),"and it costs",a1.getprice())
print("m1 is a ",m1.getmacType(),"and it costs",m1.getprice())
print("m1 is a ",m2.getmacType(),"and it costs",m2.getprice())
print("m1 is a ",m3.getmacType(),"and it costs",m3.getprice())

实际输出应显示11英寸为900、13英寸为1000、15英寸为1100。

1 个答案:

答案 0 :(得分:1)

Python字符串比较区分大小写。在您的getprice方法中,您使用了"11inch",但您给结构"11Inch"注意到了大小写i?不会比较相等。只需在各处使用相同功能,甚至更好,请查看enum模块。