简体   繁体   中英

How to define toString method?

I have just almost finished my assignment and now the only thing I have left is to define the tostring method shown here.

import math

class RegularPolygon:
  def __init__(self, n = 1, l = 1):
    self.__n = n
    self.__l = l

  def set_n(self, n):
    self.__n = n

  def get_n(self):
    return self.__n

  def addSides(self, x):
    self.__n = self.__n + x

  def setLength(self, l ):
    self.__l = l

  def getLength(self):
    return self.__l 

  def setPerimeter(self):
    return (self.__n * self.__l )

  def getArea(self):
    return (self.__l ** 2 / 4 * math.tan(math.radians(180/self.__n)))

  def toString(self):
    return
x = 3
demo_object = RegularPolygon (3, 1)
print(demo_object.get_n() , demo_object.getLength())
demo_object.addSides(x)
print(demo_object.get_n(), demo_object.getLength())
print(demo_object.getArea())
print(demo_object.setPerimeter())

Basically the tostring on what it does is return a string that has the values of the internal variables included in it. I also need help on the getArea portion too. Assignment instructions

1

2

The assignment says

... printing a string representation of a RegularPolygon object.

So I would expect you get to choose a suitable "representation". You could go for something like this:

return f'{self.__n+2} sided regular polygon of side length {self.__l}'

or as suggested by @Roy Cohen

return f'{self.__class__.__name__}({self.__n}, {self.__l})'

However , as @Klaus D. wrote in the comments, Python is not Java, and as such has its own standards and magic methods to use instead.

I would recommend reading this answer for an explanation between the differences between the two built-in string representation magic-methods: __repr__ and __str__ . By implementing these methods, they will automatically be called whenever using print() or something similar, instead of you calling .toString() every time.


Now to address the getters and setters. Typically in Python you avoid these and prefer using properties instead. See this answer for more information, but to summarise you either directly use an objects properties, or use the @property decorator to turn a method into a property.

Edit

Your area formula is likely an error with order-of-operations. Make sure you are explicit with which operation you're performing first:

return self.__l ** 2 / (4 * math.tan(math.radians(180/self.__n)) )

This may be correct:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM