是否可以像嵌套函数一样在类中使用import ?



我尝试在多边形类中导入数学模块并得到一个错误。所以类和函数一样有局部作用域。现在我觉得这很愚蠢,因为函数和类是两件事,但我怎么能实现这样的东西,而不是在edge_length和apothem中分别导入数学两次,而不是在全局作用域(外部作用域)中导入数学。

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

我想知道是否可以创建它,如果多边形是一个嵌套函数。

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()

是否有可能在类中这样做,而不分别在edge_length和apothem中导入数学两次,并且不在全局作用域中导入数学?

任何帮助都是感激的谢谢!

应该把import语句放在文件的顶部。

话虽如此,请记住导入的符号将在其导入的作用域中可用。在这种情况下,是一个类范围。

如果您仍然决定将导入放入类中,则必须使用self或类名来访问math(使用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

如果你问我的话,它看起来有点丑。

最新更新