Python中,使用类B中的类A实例的属性

Python中,使用类B中的类A实例的属性,python,class,attributes,Python,Class,Attributes,我正试图掌握Python中OOP的诀窍,目前正在编写一个简单的2D有限元分析程序 首先,我创建了两个名为节点和元素的类,其属性如代码所示。Elements类包含一个名为length的属性,该属性必须基于开始节点和结束节点的x和y坐标进行计算。这些坐标包含在用户输入的节点类的两个实例中 我的第一个问题是如何将这些元素传递到Elements类中,以供计算元素(杆或梁)长度的calc_length方法使用 我找不到答案的第二个问题是,如果使用相应的方法计算元素类的\uuuu init\uuuu()中的

我正试图掌握Python中OOP的诀窍,目前正在编写一个简单的2D有限元分析程序

首先,我创建了两个名为
节点
元素
的类,其属性如代码所示。
Elements
类包含一个名为length的属性,该属性必须基于开始节点和结束节点的x和y坐标进行计算。这些坐标包含在用户输入的
节点
类的两个实例中

我的第一个问题是如何将这些元素传递到
Elements
类中,以供计算元素(杆或梁)长度的
calc_length
方法使用

我找不到答案的第二个问题是,如果使用相应的方法计算
元素
类的
\uuuu init\uuuu()
中的
self\u length
属性,是否需要声明该属性

import math as mt
import numpy as np


class Nodes:
    
    def __init__(self,number,x_glob,y_glob):
        self.number = number
        self.xGlobal = x_glob
        self.yGlobal = y_glob
      

class Elements:
    def __init__(self,number,length,start_node,end_node):
        self.number = number
        self.length = length #delare this attribute if it is created using the calc_length method?
        self.start_node = start_node
        self.end_node = end_node

      
    def calc_length(self):
        self.length = mt.sqrt((x_global_start-x_global_end)**2 + (y_global_start-y_global_end)**2 ) 

#I need to somehow pass the x_global_start,x_global_end,
#y_global_start,y_global_end to this method from two separate 
#instances of the Nodes class
此外,这是我用来创建n个节点的实例数组的代码

num_of_nodes = int(input('Enter the number of nodes: '))

#create an empty array for the "Nodes" class attributes
arr_nodes = np.zeros(shape=(num_of_nodes,3))


for i in range(num_of_nodes):
    print('Node', i,':')
    
    #User input of the global nodal coordinates
    x_global_in = input( 'Global x coordinate [m] ' )      
    y_global_in = input( 'Global y coordinate [m] ' ) 
    
    #Instantiation of the "Nodes" class
    arr_nodes[i] = Nodes(i, x_global_in, y_global_in)

我欢迎任何建议。我只是在学习编程,所以请不要太苛刻。

计算长度
应该使用
self.start\u节点
self.end\u节点
,并使用它们的
xGlobal
yGlobal
属性

class Elements:

    def __init__(self,number,length,start_node,end_node):
        self.number = number
        self.start_node = start_node
        self.end_node = end_node
        self.calc_length()

    def calc_length(self):
        self.length = mt.sqrt((self.start_node.xGlobal-self.end_node.xGlobal)**2 + (self.start_node.yGlobal-self.end_node.yGlobal)**2 ) 

谢谢你的帮助。只是一个简短的后续问题:这是在numpy数组中存储节点类实例的有效方法,还是有更好的方法?我看不出有任何理由在这里使用numpy。只要列出一个清单就行了。我是python新手,对数组在这里的功能有点困惑。我将改进代码并使用列表。再次感谢您的帮助和时间!