-1

i tried importing math module inside of polygon class and got an error. so does class have local scopes like function do. now that i think of it its pretty dumb of me cause function and class are 2 things but how can i implement something like this without importing math twice inside of both edge_length and apothem separately and without importing math in the global scope(outer scope).

class Polygon:
    import math 
     
    def __init__(self, edge, curcumradius):
        self._n = edge
        self._r = curcumradius
    
    @property
    def edge_length(self):
        self._edgelength = (2 * self._r) * math.sin(math.pi / self._n)
        return self._edgelength
     
    @property
    def apothem(self):
        self._apothem = self._r * math.cos(math.pi / self._n)
        return self._apothem

i would like to know if its possible to create it like if polygon was a nested function.

def Polygon(n, r):
    from math import pi, sin, cos

    def edge_length():
        return 2 * r * sin(pi / n)

    def apothem():
        return r * cos(pi / n)

    return apothem(), edge_length()

is it possible to do like this in a class, without importing math twice inside of both edge_length and apothem separately and without importing math in the global scope?

any help is appreciated thanks!

Jishnu
  • 106
  • 9

1 Answers1

0

You should put your import statements in the top of the file.

With that being said, have in mind that the symbols imported will be available in the scope they where imported. In this case, the scope is a class.

If you are still determined to put the import inside the class, you must use self or the class name to access math (using self.math):

class Polygon:
    import math 
     
    def __init__(self, edge, curcumradius):
        self._n = edge
        self._r = curcumradius
    
    @property
    def edge_length(self):
        # using self.math
        self._edgelength = (2 * self._r) * self.math.sin(self.math.pi / self._n)
        return self._edgelength
     
    @property
    def apothem(self):
        # using Polygon.math
        self._apothem = self._r * Polygon.math.cos(Polygon.math.pi / self._n)
        return self._apothem

Which looks a little bit ugly if you ask me.

ichramm
  • 6,437
  • 19
  • 30