如何将普通方法更改为属性方法

时间:2018-07-22 20:38:54

标签: python-3.x

我有下面的代码正在工作。

class Point:
#    """2-D Point objects."""

    def __init__(self, x=0, y=0):
 #       """Initialize the Point instance"""
        self.x = x
        self.y = y

    def get_magnitude(self):
 #       """Return the magnitude of vector from (0,0) to self."""
        return math.sqrt(self.x ** 2 + self.y ** 2)

    def __str__(self):
        return 'Point at ({}, {})'.format(self.x,self.y)

    def __repr__(self):
        return "Point(x={},y={})".format(self.x,self.y)

point = Point(x=3, y=4)
print(str(point))
print(repr(point))
print(point)
point2 = Point()
print(point2)
point3 = Point(y=9)
print(point3)

我想将get_magnitude方法更改为一个名为depth的属性方法,如下所示。

    point = Point(3, 4)
    point
Point(x=3, y=4)
    point.magnitude
5.0
    point3 = Point(y=9)
    point3.magnitude
9.0

我该怎么做?

1 个答案:

答案 0 :(得分:1)

import math

class Point:
    """2-D Point objects."""

    def __init__(self, x=0, y=0):
        """Initialize the Point instance"""
        self.x = x
        self.y = y

    @property
    def magnitude(self):
        """Return the magnitude of vector from (0,0) to self."""
        return math.sqrt(self.x ** 2 + self.y ** 2)

    def __str__(self):
        return 'Point at ({}, {})'.format(self.x,self.y)

    def __repr__(self):
        return "Point(x={},y={})".format(self.x,self.y)

point = Point(3, 4)
print(point)
print(point.magnitude)
point3 = Point(y=9)
print(point3.magnitude)

打印:

Point at (3, 4)
5.0
9.0