Reputation: 35
I am trying to create a child class called Beams
which is an extension of the Elements
class. The latter computes the length of the element and stores it as an attribute of the Elements
class. I would like to somehow pass the length
to the child class. What is the right way to do it?
Please note: my code does not instantiate the Elements
class directly. Rather its attributes are used in the instances of the Beam
class through inheritance.
class Elements:
def __init__(self,number,start_node,end_node,e_modulus,cs_area):
self.number = number
self.start_node = start_node
self.end_node = end_node
self.e_modulus = e_modulus
d_x = end_node.x_glob - start_node.x_glob
d_y = end_node.y_glob - start_node.y_glob
self.length = mt.sqrt(d_x**2 + d_y**2)
self.alpha = mt.atan2(d_y, d_x)
r1 = mt.cos(self.alpha)
r2 = mt.sin(self.alpha)
self.rot_matrix = np.array([[r1, r2, 0, 0, 0, 0],
[-r2, r1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, r1, r2, 0],
[0, 0, 0, -r2, r1, 0],
[0, 0, 0, 0, 0, 1]])
class Beam(Elements):
def __init__(self,number,start_node,end_node,e_modulus,cs_area,second_mom_of_area):
super().__init__(number,start_node,end_node,e_modulus,cs_area)
self.second_mom_of_area = second_mom_of_area
k1 = (e_modulus*cs_area)/length
k2 = (12*e_modulus*second_mom_of_area)/(length**3)
k3 = (6*e_modulus*second_mom_of_area)/(length**2)
k4 = (4*e_modulus*second_mom_of_area)/(length)
k5 = (2*e_modulus*second_mom_of_area)/(length)
self.loc_stiff_matrix = np.array([[ k1, 0, 0, -k1, 0, 0],
[ 0, k2, k3, 0, -k2, -k3],
[ 0, k3, k4, 0, -k3, k5],
[-k1, 0, 0, k1, 0, 0],
[ 0, -k2, -k3, 0, k2, 0],
[ 0, k3, k5, 0, -k3, k4]])
Upvotes: 0
Views: 789
Reputation: 981
Everything you define in your parent class is inherited by the child and, unless explicitly modified in the body of the child, they are directly accessible as attributes.
In your case:
beam = Beam(**kwargs)
print(beam.length)
# or
print(getattr(beam, "length"))
should work.
Upvotes: 1