【问题标题】:Printing a subclass string打印子类字符串
【发布时间】:2013-11-29 08:07:41
【问题描述】:

我有一个“超类”和一个“子类”

class Triangle(GeoMetricObject):
  def __init__(self,side1=1,side2=1,side3=1):
        super().__init__()
        self.__side1= side1
        self.__side2= side2
        self.__side3= side3
  def getPerimeter(self,side1,side2,side3):
        return side1+side2+side3
  def __str__(self):
        return super().__str__()+"side1:"+(self.__side1)+"side2:"+(self.__side2)+"side3:"+(self.__side3)

从几何对象导入几何对象,三角形

第二个文件,运行上面的模块。

def main():
s1= int(input("What is the length  of the first side? "))
s2= int(input("What is the length  of the second side? "))
s3= int(input("What is the length  of the third side? "))
side1=s1
side2=s2
side3=s3
t1 = Triangle(s1,s2,s3)
l = GeoMetricObject()
print("Default color of Triangle:",l.getColor())
print("The Perimeter of Triangle : ",t1.getPerimeter(side1,side2,side3,))
print(Triangle())

main()

我的问题是我似乎可以正确地从子类 str 获得正确的输出。它给了我这个错误;

Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 14, in main
File "c:\Users\Fergus\Desktop\GeometricObject.py", line 26, in __str__
return super().__str__()+"side1:"+(self.__side1)+"side2:"+(self.__side2)+"side3:"+(self.__side3)
builtins.TypeError: Can't convert 'int' object to str implicitly

我不确定如何解决此问题。我不是一个很好的程序员,主要是生物学家。

【问题讨论】:

    标签: class subclass python-3.3 superclass


    【解决方案1】:

    当您进行加法时,您正试图将 int 隐式转换为字符串。您不能在这些不同类型之间进行添加。但是,如果您将整数转换为字符串,没问题

    替换这个:

    super().__str__()+"side1:"+(self.__side1)+"side2:"+(self.__side2)+"side3:"+(self.__side3)
    

    通过这个:

    super().__str__()+"side1:"+str(self.__side1)+"side2:"+str(self.__side2)+"side3:"+str(self.__side3)
    

    没有 python3 可以检查,但它应该可以工作。

    【讨论】:

    • 谢谢!我认为它无法转换,因为侧面在技术上是整数,但我想如果它只是作为输出打印,则需要满足条件。
    猜你喜欢
    • 1970-01-01
    • 2014-12-26
    • 2019-03-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多