user10019227
user10019227

Reputation: 117

How to change a normal method into a property method

I have the below code which is working.

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)

I want to change the get_magnitude method into a property method named magnitude which works as shown below.

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

How would I do this?

Upvotes: 0

Views: 128

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

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)

Prints:

Point at (3, 4)
5.0
9.0

Upvotes: 1

Related Questions