类中的Python类
我有一个模拟python代码,为了便于使用,我想将其转换为类结构 现在,我的问题是:我知道如何设置一个普通类,即:类中的Python类,python,class,Python,Class,我有一个模拟python代码,为了便于使用,我想将其转换为类结构 现在,我的问题是:我知道如何设置一个普通类,即: class simulation: def __init__(self, name): self.name = name def geometry(self): def calculation(self): etc. …但如何合并子实例,即圆形、矩形 基本上,最后,我希望能够编写类似于:simulation.geometry.cir
class simulation:
def __init__(self, name):
self.name = name
def geometry(self):
def calculation(self):
etc.
…但如何合并子实例,即圆形、矩形
基本上,最后,我希望能够编写类似于:simulation.geometry.circle(…)
这就是我迄今为止所尝试的:
class Simulation:
"""Outer Class"""
def __init__(self, name):
self.name = name
## instantiating the 'Inner' class
#self.geometry = self.Geometry()
def print_name(self):
print("name: ", self.name)
class Geometry(Simulation):
"""Inner Class"""
def circle(self, radius,center):
print("name of simulation: ", self.name)
print("radius: ", center)
print("position: ", center)
def rectangle(self, center):
print("position: ", center)
现在,如果我尝试:
## instantiating the outer class
sim = Simulation("version_1")
## instantiating the inner class
geo = sim.Geometry()
geo.circle(radius=10,center=[0,0])
我得到一个错误:
…但我得到了一个错误:
TypeError:init()缺少1个必需的位置参数:“name”
您继承的是
模拟
,而不重写\uuuu初始化
构造函数。由于不重写,因此它使用模拟
中的\uuuu init\uuuu
,该参数为1
请注意,几何体
不能从模拟
继承,因为它是几何体的一个组件。如果您愿意,您应该将类几何体
移出模拟
。但是,如果您希望能够调用Simulation.Geometry…
,而这是通过继承无法实现的,那么您可能不希望这样做
如果您希望能够调用
几何体的模拟的属性
,您可以通过说出模拟.attribute
来引用它,但是您不能像这样访问实例变量。类几乎不需要像这里这样以嵌套方式定义。将类定义分开可以更容易地对它们的关系进行推理。@PatrickHaugh你如何继承自我。从一节课到下一节课?你介意重写一下我的小例子吗?非常感谢。您可以将模拟
传递给几何体。\uuuu init\uuuu
或将其传递给几何体的各个方法。如果我不知道你到底想做什么,我就不能真正推荐一个设计。试着想想“在”Simulation
下”的对象是否真的需要知道它们的Simulation
s,或者它们接受方法的参数是否足够。@PatrickHaugh我想用所有常规参数(即路径、模拟大小、模拟时间等)初始化一个模拟类然后,这些参数应交给所有特定类,如几何体类,您可以在其中设置几何体,即半径等。这些特定类需要不时访问常规参数,以便知道例如将数据保存到何处。我希望这能让我更清楚地知道我在寻找什么?@PatrickHaugh请查看更新的答案。不过,我仍然不明白如何更改代码以使其正常工作。我需要如何修改代码?谢谢!您提到希望能够像调用模块一样调用Simulation.Geometry.circle()
。但是您也可以通过说sim=Simulation('name')
来实例化这些类。您想实例化这些对象并将其用作对象,还是希望类充当一组方法的结构?我不熟悉术语,因此我将描述您希望我能够做到的:我希望使用所有常规参数初始化模拟类,然后,这些参数应传递给所有特殊类,如几何体类,您可以在其中设置几何体,即半径等。
line 34, in <module>
geo = sim.Geometry()
TypeError: __init__() missing 1 required positional argument: 'name'
class Simulation:
# parent class
def __init__(self, name):
self.name = name
## instantiating the 'Inner' class
#self.geometry = self.Geometry()
def print_name(self):
print("name: ", self.name)
class Geometry(Simulation):
# child class
def circle(self, radius,center):
print("name of simulation: ", self.name)
print("radius: ", center)
print("position: ", center)
def rectangle(self, center):
print("position: ", center)