0

This is my code:

class test(object):
    """\
given angle is within 360 degrees"""
    def __init__(self, angle):
        self.angle = angle
    def __str__(self):
        return "This is going to be positive {}".format(self.angle)
    def __neg__(self):
        """\
    when given a negative angle it will be translated into a positive"""
        if self.angle < 0:
            return test(self.angle + 360)
angle = test(-100)
print(angle)

The output is:

This is going to be positive -100

How would I go about getting an angle of 260 instead of this negative? I'm stumped.

4

1 回答 1

1

You need to do the negative check in the constructor (__init__). __neg__ should return a new test that is the negative of self.

class test(object):
    """\
given angle is within 360 degrees"""
    def __init__(self, angle):
        self.angle = angle % 360
    def __str__(self):
        return "This is going to be positive {}".format(self.angle)
    def __neg__(self):
        """\
    when given a negative angle it will be translated into a positive"""
        return test(-self.angle)
angle = test(-100)
print(angle)
于 2013-04-23T19:27:50.410 回答