0

I'm currently doing a python simulation project. For example I have class tank with the attributes temperature , volume and pressure. But the thing is that volume is a result of a certain operation between temperature and pressure. So how can I insert the volume as attribute after calculating it using the other two attributes I mentioned. The basic syntax is this:

 def __init__(self, temp, pressure, volume)

and for example, to calculate volume we have volume=temp*pressure ( It's obviously not the right formula just for the sake of simplicity)

Thank you for your help

I tried to create a method for volume under class tank , but I dont know if thats the right approach or I should try something else.

coconut
  • 27
  • 8
P.Haidar
  • 1
  • 1
  • 2
    Does this answer your question? [How does the @property decorator work in Python?](https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work-in-python) – matszwecja Jun 15 '23 at 10:44

2 Answers2

0

In your Tank class, you can calculate the volume attribute based on the provided temperature and pressure attributes using a separate method. Here's an example:

class Tank:
def __init__(self, temp, pressure):
    self.temp = temp
    self.pressure = pressure
    self.volume = self.calculate_volume()

def calculate_volume(self):
    return self.temp * self.pressure

By defining the calculate_volume method, you can easily compute the volume attribute using the given temperature and pressure values. Whenever you create a Tank object, the volume will be automatically calculated for you.

  • 1
    Nice answer! Please consider fixing the formatting and adding some explanations. – Geom Jun 15 '23 at 11:18
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 15 '23 at 17:57
0

You cannot both provide volume and calculate it. It's either or situation. The program will be executed sequentially so even if you provide and calculate only one value will remain in the end. So instead just take temp and pressure as inputs and create a separate method that can calculate volume.

class Tank():
    def __init__(self, temp, pressure):
        self.temp = temp
        self.pressure = pressure
        self.volume = self.get_volume(temp, pressure)
    # Calculate volume
    def get_volume(self, temp, pressure):
        volume = temp*pressure
        return volume
    # Just for printing atributes  
    def get_atributes(self):
        print('Temp: ', self.temp)
        print('Pressure: ', self.pressure)
        print('Volume: ', self.volume)
    
tank = Tank(temp=10, pressure=2)
tank.get_atributes()

Output:

Temp:  10
Pressure:  2
Volume:  20
Geom
  • 1,491
  • 1
  • 10
  • 23