How to make sure that no other instances have the same name from a class

Question:

class Satellite:
  
  def __init__(self, message):
    print(message)
    self.name = input("name: ").title()
    self.lbs = int(input("lbs: "))
    self.speed = int(input("speed: "))

lstSat = []
e= input("Would you like to create satellites? If yes, type O. If not, type another letter: ").lower()
i=0
while e=="o":
    lstSat.append(Satellite("Info for satellite "+str(i+1)))
    i+=1
    e= input("Type O to create another satellite: ").lower()

Hello,

How can I make sure that 2 Satellites cannot be the same?

Asked By: metal

||

Answers:

I would go for iteration in list and check names with every satellite

...
while e=="o":
    satellite = Satellite("Info for satellite " + str(i+1))
    if check_reapeated_name(lstSat, satellite.name): # see definition of function bellow
        lstSat.append(satellite)
    else:
        # here do some output or error handling
    ...
...

and the definition of check_reapeated_name() would be something like this:

def check_reapeated_name(lstSat, satellite_name):
    for i in lstSat:
        if i.name == satellite_name:
             return False
    return True
Answered By: Kaldesyvon

Please don’t ask for user input during class construction. Much better to acquire the values elsewhere then use a straightforward constructor based on the user’s input values.

In order to determine repetition, you need to override the eq dunder method.

Try this:

class Satellite:
    def __init__(self, name, lbs, speed):
        self._name = name
        self._lbs = lbs
        self._speed = speed
    def __eq__(self, other):
        if isinstance(other, str):
            return self._name == name
        if isinstance(other, type(self)):
            return self._name == other._name
        return False
    def __str__(self):
        return f'Name={self._name}, lbs={self._lbs} speed={self._speed}'

lstSat = []

PROMPT = 'Would you like to create satellites? If yes, type O. If not, type another letter: '

while input(PROMPT) in 'Oo':
    name = input('Name: ').title()
    if name in lstSat:
        print(f'{name} already in use')
    else:
        lbs = int(input('lbs: '))
        speed = int(input('Speed: '))
        lstSat.append(Satellite(name, lbs, speed))

for satellite in lstSat:
    print(satellite)
Answered By: Cobra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.