我尝试在多边形类中导入数学模块,但出现错误。那个么这个类和函数do一样具有局部作用域。现在我想起来了,我真是太傻了,因为函数和类是两件事,但是我如何实现这样的东西,而不在edge_length和Apothes中分别导入两次数学,也不在全局范围(外部范围)中导入数学
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和Apothes中分别导入两次数学,也不在全局范围内导入数学
谢谢你的帮助 谢谢
您应该将导入语句放在文件的顶部
尽管如此,请记住,导入的符号将在其导入的范围内可用。在本例中,作用域是一个类
如果仍然决定将导入放入类中,则必须使用
self
或类名来访问math
(使用self.math
):如果你问我的话,它看起来有点难看
相关问题 更多 >
编程相关推荐