Как вызвать объект других классов в новом классе в PythonPython

Программы на Python
Ответить
Anonymous
 Как вызвать объект других классов в новом классе в Python

Сообщение Anonymous »

Я создал эти три класса Tether, Mass и Spring. Теперь в классе main() я хочу объединить все это вместе, чтобы имитировать созданный ими гармонический осциллятор, но я не уверен, нужно ли и как мне реализовать переменные других классов в основном, такие как self .tx и self.ty класса Tether() или self.x, self.y и т. д. из Mass() и так далее, поскольку вначале следует инициировать связанную систему пружинных масс, чтобы Я могу добавить начальную скорость позже, чтобы начать симуляцию.
Функции в начале предназначены только для получения пользовательского ввода, я также реализую их здесь, чтобы вы могли попробовать код, если вам нужно.
def Grid():
global grid
grid = np.zeros((2,1))
return grid

def Quantity():
try:
global quantity
quantity = int(input('How many masses do you want to simulate?') )
#grid = np.delete(grid1,0,1)

except:
print('You must insert integers only!')
Quantity()
return quantity

def Tether_properties():
global tether
tether = []
try:
global x,y
x = int(input('Where do you want to place your x coordinate of the tether?'))
y =int(input('Where do you want to place your y coordinate of the tether?'))
t = Tether(x,y)
tether.append(t)
#tether.append(t)
except ValueError:
print('You must insert integers only!')
Tether_properties()

def Mass_properties():
global masses
masses = []
for i in range(quantity):
try:
global x, y, vx, vy, w
x = int(input('Where do you want to place your x coordinate of your mass?' ))
y = int(input('Where do you want to place your y coordinate of your mass?'))
vx = int(input('How fast do you want your Mass to move in direction of x?' ))
vy = int(input('How fast do you want your Mass to move in direction of y?'))
weight = int(input('How much do you want the Mass to weigh?'))
if weight == 0:
print('Mass must be an integer > 0 for the Mass!')
Mass_properties
else:
w = weight
global m
m = Mass(x,y,vx,vy,w)
masses.append(m)
except ValueError:
print('You must insert integers only!')
Mass_properties()

def Spring_properties():
global lx,ly,length,stiffness, spring_props
spring_props = []
for i in range(quantity):
if i == 0:
lx = tether[0].x_t_coord - masses[0].x_coord
ly = tether[0].y_t_coord - masses[0].y_coord
vector = np.array([[lx],[ly]])
length = nl.norm(vector)
try:
stiffness = int(input('What stiffness do you want your spring to have? '))
except ValueError:
print('You must insert integers only for the stiffnes!')
Spring_properties()
else:
lx = masses[i-1].x_coord - masses.x_coord
ly = masses[i-1].y_coord - masses.y_coord
vector = np.array([[lx],[ly]])
length = nl.norm(vector)
try:
stiffness = int(input('What stiffness do you want your spring to have? '))
except ValueError:
print('You must insert integers only for the stiffnes!')
Spring_properties()
l = Spring(lx,ly,length,stiffness)
spring_props.append(l)

class Tether():

def __init__(self,x,y):
self.tx = x
self.ty = y

@property
def x_t_coord(self):
return self.tx

@property
def y_t_coord(self):
return self.ty

класс Mass():
def __init__(self,x,y,vx,vy,w):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.w = w

@property
def x_coord(self):
return self.x

@property
def y_coord(self):
return self.y

@property
def x_velo(self):
return self.vx

@property
def y_velo(self):
return self.vy

@property
def mass(self):
return self.w

класс Spring():
def __init__(self,lx,ly,length,stiffness):
self.lx = lx
self.ly = ly
self.length = length
self.stiffness = stiffness

@property
def lx_coord(self):
return self.lx

@property
def ly_coord(self):
return self.ly

@property
def length_value(self):
return self.length

@property
def stiffness_value(self):
return self.stiffness

class main():

def __init__(self):
pass


Подробнее здесь: https://stackoverflow.com/questions/705 ... -in-python
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»