Nmbh 发表于 2020-6-18 16:54:36

如何像__repr__()一样输入实例名返回列表?

本帖最后由 Nmbh 于 2020-6-18 16:55 编辑

我写了段代码想实现《零基础学习python》第38讲动动手第0题的要求。
但是在代码中我用Point类中使用__repr__(),想实现但用户输入类的实例化名称时以列表形式返回坐标,但发现__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

class Line:
      def __init__(self,point1 = , point2 = ):
            self.point1 = point1
            self.point2 = point2
      
      def getLen(self):
            length = m.sqrt((self.point1-self.point2)**2 + (self.point1-self.point2)**2)
            return length

a = Point(1,1)
b = Point(5,4)
c = Line(a,b)
c.getLen()

Stubborn 发表于 2020-6-18 17:09:37

分为两个情况,要么返回给人看,要么返回给程序看。对应的__str__和__repr__ 。都是字符串,重要你怎么展示这个字符串,

我看你的代码和你的问题没有任何关联,如果是问报错问题,你的Point没有实现__getitem__不能用索引取值,用point.xpoint.y是取值

Nmbh 发表于 2020-6-18 18:24:16

我试着用eval回避了__repr__()输出为字符串的问题
import math as m
class Point:
      def __init__(self,x=0,y=0):
            self.x = x
            self.y = y
      def __repr__(self):
      return str()

class Line:
      def __init__(self,point1 = , point2 = ):
            if not isinstance(point1,list):
                point1 = eval(str(point1))
            if not isinstance(point2,list):
                point2 = eval(str(point2))            
            self.point1 = point1
            self.point2 = point2
      
      def getLen(self):
            length = m.sqrt((self.point1-self.point2)**2 + (self.point1-self.point2)**2)
            return length
a = Point(1,1)
b = Point(5,4)
c = Line(a,b)
c.getLen()

xiaofeiyu 发表于 2020-6-18 21:58:11

把这个:
class Point:
      def __init__(self,x=0,y=0):
            self.x = x
            self.y = y
      def __repr__(self):
      return
改成:
class Point:
      def __init__(self,x=0,y=0):
            self.x = x
            self.y = y
      def __repr__(self):
      return str()

不就行了
页: [1]
查看完整版本: 如何像__repr__()一样输入实例名返回列表?