【问题标题】:Is it possible to use import inside of a class like a nested function? [duplicate]是否可以像嵌套函数一样在类中使用导入? [复制]
【发布时间】:2021-11-28 12:26:12
【问题描述】:

我尝试在多边形类中导入数学模块,但出现错误。类也有像函数一样的局部范围。现在我认为它对我来说很愚蠢,因为函数和类是两件事,但是我怎么能实现这样的东西,而不需要在 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 中分别导入两次数学,也无需在全局范围内导入数学?

感谢任何帮助 谢谢!

【问题讨论】:

  • 它给你的错误是什么?
  • 顺便说一句,为什么不在文件顶部包含数学?
  • 所以你不想在外部作用域中导入它,但你也不想在每个内部作用域中导入它。那你到底想要什么?
  • 是的,类有范围。函数定义在类范围内。不过,我认为这不是您的实际问题
  • @kaya3 我想知道我们是否可以像嵌套函数一样实现它

标签: python python-3.x


【解决方案1】:

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

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

如果你还是下定决心把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

如果你问我,这看起来有点难看。

【讨论】:

  • 我已经澄清了我的问题,我在问它是否可以像嵌套列表一样进行
  • 在这种情况下,您将不得不使用self.sinself.pi 等。
猜你喜欢
  • 1970-01-01
  • 2012-08-15
  • 2013-01-20
  • 2018-11-12
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2021-03-28
相关资源
最近更新 更多