添加来自不同类的两个值


class PolygonInteriorAngle(object):
def __init__(self, x):
self.x = self

def FindInteriorAngle(self):
degrees = int((x - 2) * 180)
interior = int(degrees / x)
return interior

def PrintInterior(self):
print("interior angle: " + str(self.FindInteriorAngle()))
class PolygonExteriorAngle(object):
def __init__(self, x):
self.x = self

def FindExteriorAngle(self):
exterior = int(360 / x)
return exterior

def PrintExterior(self):
print("exterior angle: " + str(self.FindExteriorAngle()))
class AngleAddition(object):
def __init__(self, x):
self.x = self

def Add(self):
sum = int(interior + exterior)
return sum

def PrintAdd(self):
print("sum of interior and exterior: " + str(self.Add()))

if __name__ == "__main__":
x = int(input("enter: "))
intObj = PolygonInteriorAngle(x)
intObj.FindInteriorAngle()
intObj.PrintInterior()
extObj = PolygonExteriorAngle(x)
extObj.FindExteriorAngle()
extObj.PrintExterior()
addObj = AngleAddition(x)
addObj.Add()
addObj.PrintAdd()

这两个类(PolygonInteriorAngle和PolygonExteriorAngle)都工作得很好,他们打印他们所期望的。我想在AngleAddition类中做的是添加从其他两个类获得的最终值(内部和外部)。我认为把它们放在不同的课上效率很低,但这是我的计算机科学老师让我做的,我不确定如何在新课上使用另一个课上的值。如果x = 6,就得到120和60。使用AngleAddition,我想打印180。

总评:

  1. 您需要非常仔细地检查实例方法中的变量。例子:
def Add(self):
sum = int(interior + exterior)
return sum

interiorexterior都没有在实例方法参数中指定。

  1. 我同意User: Tim Roberts的评论。要么你创建一个基类angle;让"内/外角"类从"角度"继承。类,或者只对内角和外角使用Angle类。这取决于你想如何为内部/外部角度类编写__init__方法。

  2. 注意,我重写了魔术方法来执行两个角度的和。还有其他方法可以做到这一点,因为在我的方法中,+操作符正在被重新定义。

无论如何:

class AngleBase:
def __init__(self,angle):
self.angle=angle
def __add__(self,angleobj):
return int(self.angle+angleobj.angle)
class PolygonInteriorAngle(AngleBase):
def __init__(self, side):
degrees = int((side - 2) * 180)
interior = int(degrees / side)
AngleBase.__init__(self,interior)

def FindInteriorAngle(self):
return self.angle

def PrintInterior(self):
print("interior angle: " + str(self.angle))
class PolygonExteriorAngle(AngleBase):
def __init__(self, side):
exterior = int(360 / side)
AngleBase.__init__(self,exterior)

def FindExteriorAngle(self):
return self.angle

def PrintExterior(self):
print("exterior angle: " + str(self.angle))
class AngleAddition:
def __init__(self, x):
pass

def Add(self,interior, exterior):
sum = int(interior + exterior)
return sum

def PrintAdd(self,interior, exterior):
print("sum of interior and exterior: " + str(self.Add(interior, exterior)))

if __name__ == "__main__":
x = int(input("enter: "))
intObj = PolygonInteriorAngle(x)
print(intObj.angle)
intObj.FindInteriorAngle()
intObj.PrintInterior()
extObj = PolygonExteriorAngle(x)
extObj.FindExteriorAngle()
extObj.PrintExterior()
addObj = AngleAddition(x)
addObj.Add(extObj,intObj)
addObj.PrintAdd(extObj,intObj)

相关内容

  • 没有找到相关文章

最新更新