Почему изменяются все экземпляры моего класса, хотя следует изменить только атрибуты одного объекта?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему изменяются все экземпляры моего класса, хотя следует изменить только атрибуты одного объекта?

Сообщение Anonymous »

У меня есть 2 объекта (1 и 2) из ​​одного класса и 1 объект (A) из другого класса. Когда я использую функцию из A, чтобы изменить атрибуты объекта 1, атрибуты объекта 2 изменяются, и я понятия не имею, почему.

Код: Выделить всё

import numpy as np

allflows = []
processunits = []

class Flow:
def __init__(self, name = '', components = '', flow_type = '',
temperature=25, pressure = 1, composition = [1], origin = None,
destination = None, mass_flow_rate = 0, elec_flow_rate = 0,
heat_flow_rate = 0, is_calc_flow = False):
self.attributes = {'name' : name, 'components' : components, 'flow_type' :
flow_type, 'temperature' : temperature, 'pressure':
pressure, 'composition' : composition, 'origin' :
origin, 'destination' : destination, 'mass_flow_rate':
mass_flow_rate, 'elec_flow_rate' : elec_flow_rate,
'heat_flow_rate': heat_flow_rate}
self.is_calc_flow = is_calc_flow

def set_destination(self, Destination_unit):
if self.attributes['destination'] == Destination_unit.name and self.attributes['name'] in Destination_unit.input_flows:
pass  # Do nothing if already correctly assigned
elif self.attributes['destination'] != Destination_unit.name:
if self.attributes['destination']:  # Remove from previous destination if exists
prev_unit = next((unit for unit in processunits if unit.name == self.attributes['destination']), None)
if prev_unit:
prev_unit.input_flows.remove(self.attributes['name'])
# Add to new destination
Destination_unit.input_flows.append(self.attributes['name'])
self.attributes['destination'] = Destination_unit.name
print(f"Flow {self.attributes['name']} set destination to {self.attributes['destination']}")

class Unit:
def __init__(self, name, input_flows = [], output_flows = [],
calculations = {}, expected_flows_in = [], expected_flows_out = [], coefficients = [], is_calc = False):
self.name = name
self.input_flows = input_flows
self.output_flows = output_flows
self.calculations = calculations
self.expected_flows_in = expected_flows_in
self.expected_flows_out = expected_flows_out
self.coefficients = coefficients
self.is_calc = is_calc

Unit1 = Unit('Unit 1')
Unit2 = Unit('Unit 2')
Unit1.expected_flows_in = ['A']
Unit1.expected_flows_out = ['B', 'D']
Unit1.coefficients = 0.6
def Unit1func(flow, coeff):
a_amount = flow.attributes['mass_flow_rate']
b_amount = coeff*a_amount
d_amount = a_amount - b_amount
return [{'name' : 'B', 'components' : 'B', 'mass_flow_rate' : b_amount,
'flow_type': 'Process stream', 'In or out' : 'Out'},
{'name' : 'D', 'components' : 'D', 'mass_flow_rate' : d_amount,
'flow_type': 'Process stream', 'In or out' : 'Out'}]

FlowA = Flow('A', 'A','input', 25, 1, [1], np.nan , np.nan, 1000, np.nan, np.nan)

print(f"Initial input flows of Unit2: {Unit2.input_flows}")
print(f"Initial output flows of Unit2: {Unit2.output_flows}")

FlowA.set_destination(Unit1)

print(f"Input flows of Unit2 after setting FlowA's destination to Unit1: {Unit2.input_flows}")
print(f"Output flows of Unit2 after setting FlowA's destination to Unit1: {Unit2.output_flows}")

print(Unit1)
print(Unit2)

И вывод на консоль:

Код: Выделить всё

Initial input flows of Unit2: []
Initial output flows of Unit2: []
Flow A set destination to Unit 1
Input flows of Unit2 after setting FlowA's destination to Unit1: ['A']
Output flows of Unit2 after setting FlowA's destination to Unit1: []


В идеале я бы ожидал, что будет изменен только Unit1, а Unit2 останется нетронутым с помощью set_destination. Я не знаю, что вызывает эту проблему, поскольку Unit1 и Unit2 не используют одно и то же пространство памяти, а априорный set_destination изменяет только единицу измерения в аргументе. Кто-нибудь знает, что вызывает эту проблему? Или знаете лучший обходной путь?
Заранее спасибо!

Подробнее здесь: https://stackoverflow.com/questions/792 ... bjects-att
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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