首页 > 解决方案 > 如何在内部类中调用外部类参数?

问题描述

您好,我是在 python 中使用类的初学者。我正在尝试在内部类中获取外部类参数参数。例如我有:

class Rectangle: 

  n_edges = 4

  def __init__(self, length, width):
    self.length = length
    self.width = width

  def rectangle_area(self):
    return self.length*self.width


  def rectangle_perimeter(self):
    return 2*self.length + 2*self.width
    
  class Patch:
    
    def __init__(self, cor1, cor2):
      self.cor1 = cor1
      self.cor2 = cor2
      # I want here to get length and width

所以我想在 Patch 类中有 Rectangle 类的长度和宽度参数,而不是在 Patch 的构造函数中将它们作为参数传递

任何想法 ?

非常感谢 !

标签: pythonclass

解决方案


首先用第一类 i 保存 python 文件。e 将矩形类保存在 python 文件中(rectangle.py)。然后在其他python文件中导入矩形。py 文件,所以你可以使用矩形类的所有功能


推荐阅读