【问题标题】:I am not getting the desired Result我没有得到想要的结果
【发布时间】:2022-09-29 22:32:17
【问题描述】:
    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        @classmethod
        def zero(cls):
            return cls(0, 0)


point = Point.zero()

我应该得到 Point(0, 0) 但我没有得到它

  • \"我没有得到想要的结果\"不是一个好的问题标题。

标签: python-3.x


【解决方案1】:

你这样做,但你生成的是一个类对象:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def zero(cls):
        return cls(0, 0)

origin = Point.zero()

origin.x -> 0
origin.y -> 0

【讨论】:

    【解决方案2】:

    你得到了正确的Point 对象。要确认,请打印type(point) 并打印point.xpoint.y。但它的表示默认为object.__repr__ 提供的(所有类都从object 类继承)。实现您自己的__str____repr__。 (见区别here):

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        @classmethod
        def zero(cls):
            return cls(0, 0)
    
        def __repr__(self) -> str:
            return f"Point{self.x, self.y}"
    
    
    point = Point.zero()
    print(point)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多