Use a class method from a concatenated string

Asked

Viewed 46 times

-1

Hello, I’m new to Pyhon...

I have a class called Car, and in it I have a method called name that returns the name of my object. Ex.: carro_1.name() = returns the name of the car.

I have the objects, carro_1, carro_2, carro_3...

Running carro_1.name() I get the name of the car.

I have a list with prices of all cars, in order, price in position 1 is for the carro_1, position 2 is for the carro_2 etc

I found the lowest price on my list and your position.

with this I concatenei 'carro_' + 'position + 1 ' For example: the lowest price is in heading 0 concatenei: 'carro_' + '1', got 'carro_1'

only that I’m having trouble accessing the name() method referring to the string I got.

  • Yes, but that doesn’t have to be done. There are better ways to manage this dynamic access to object functions. Could [Dit] the question and add an example to better understand what you are trying to do?

  • I edited, please see if it’s clearer.

  • And how is this price list generated? Why is this price not part of the car object itself?

  • the price is generated by the user, because it has some variables in the generation of prices.. But I would know a way for me to access the object the way I’m doing, or a similar way.

  • Use a string to call an object of the same name.

1 answer

0


When we program in object orientation, we use Getters and Setters to obtain values within a variable and encapsulation of the data.... I recommend studying object-oriented programming to understand the modus operandi of this paradigm.

Example of property with get and set:

class NaoSei:

   def __init__(self, algo):
        self._algo = algo

   @property  # Getter
   def algo(self):
       return self._algo

   @algo.setter  # Setter
   def algo(self, value):
       self._algo = value

And with that you will be able to call your property the right way:

c = NaoSei('teste')
print(c.algo)

This way your code will be correctly following the object orientation paradigm, will encapsulate your class, and will facilitate the maintenance/implementation of the code.

Want to limit to only the class can manipulate the property? Simple! remove the Setter.
Need to make a calculation when setting the property? Just implement in Setter.

Example:

   @algo.setter  # Setter
   def algo(self, value):
       value = 'outro ' + value
       self._algo = value

Then just do that to arrow it:

c = NaoSei('teste')
print(c.algo)
>teste
c.algo = 'teste'
print(c.algo)
>outro teste

Browser other questions tagged

You are not signed in. Login or sign up in order to post.