是否可以像嵌套函数一样在类内部使用导入?

2024-10-01 00:14:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在多边形类中导入数学模块,但出现错误。那个么这个类和函数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中分别导入两次数学,也不在全局范围内导入数学

谢谢你的帮助 谢谢


Tags: 函数selfreturndefpi数学mathsin
1条回答
网友
1楼 · 发布于 2024-10-01 00:14:31

您应该将导入语句放在文件的顶部

尽管如此,请记住,导入的符号将在其导入的范围内可用。在本例中,作用域是一个类

如果仍然决定将导入放入类中,则必须使用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

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

相关问题 更多 >