|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Nmbh 于 2020-6-18 16:55 编辑
我写了段代码想实现《零基础学习python》第38讲动动手第0题的要求。
但是在代码中我用Point类中使用__repr__(),想实现但用户输入类的实例化名称时以列表形式返回[x,y]坐标,但发现__repr__和__str__一样只能返回字符串。
请问有没有什么魔法方法能够返回非字符串(比如数字、列表)
- import math as m
- class Point:
- def __init__(self,x=0,y=0):
- self.x = x
- self.y = y
- def __repr__(self):
- return [self.x,self.y]
- class Line:
- def __init__(self,point1 = [0,0], point2 = [0,0]):
- self.point1 = point1
- self.point2 = point2
-
- def getLen(self):
- length = m.sqrt((self.point1[0]-self.point2[0])**2 + (self.point1[1]-self.point2[1])**2)
- return length
- a = Point(1,1)
- b = Point(5,4)
- c = Line(a,b)
- c.getLen()
复制代码
把这个:
- class Point:
- def __init__(self,x=0,y=0):
- self.x = x
- self.y = y
- def __repr__(self):
- return [self.x,self.y]
复制代码
改成:
- class Point:
- def __init__(self,x=0,y=0):
- self.x = x
- self.y = y
- def __repr__(self):
- return str([self.x,self.y])
复制代码
不就行了
|
|