Search code examples
pythonloopsclassobject

Looping through class objects to find an object with certain attributes in python


I am trying to find a way to loop through the different skills for my game my code is below


class Skill:
  def __init__(self, user, desc, effect, ea, amount, am):
    self.user = user
    self.desc = desc
    self.effect = effect
    self.amount = amount
    self.am = am

s1 = Skill("user1", "lightning blade", "Decrease", "health", 165419, 34743)
s2 = Skill("user1", "hurricane dash", "Decrease", "Speed", 113479, 95791)
s3 = Skill("user2", "earthquake", "Increase", "attack", 163479, 35791)

#want to loop through class object to auto find "lightning blade" skill

the objective is to print / use the skill object with desc attribute as 'lightning blade' from the list of objects above ignoring the "hurricane dash" from the same user and user2's skill "earthquake" when "lightning blade" is found I also want to get the amount and am attributes


Solution

  • If the skill objects are dynamic or real time, you can code it as shown below:

    class Skill:
      skill_objs = []
      # variables like 'skill_objs' are called class variables that are common among all the objects of a particular class
      def __init__(self, user, desc, effect, ea, amount, am):
        self.user = user
        self.desc = desc
        self.effect = effect
        self.amount = amount
        self.am = am
        # 'self' here refers to the current object
        Skill.skill_objs.append(self)
    
    s1 = Skill("user1", "lightning blade", "Decrease", "health", 165419, 34743)
    s2 = Skill("user1", "hurricane dash", "Decrease", "Speed", 113479, 95791)
    s3 = Skill("user2", "earthquake", "Increase", "attack", 163479, 35791)
    
    wanted_skill_obj = None
    # class variables can be accessed using the syntax <class_name>.<variable_name> like 'Skill.skill_objs'
    for skill in Skill.skill_objs:
       if(skill.desc == 'lightning blade'):
          wanted_skill_obj = skill
          break;
    # to get the attributes of the wanted skill
    if(wanted_skill_obj == None):
       print("No skill found!")
    else:
       print('desc: ',wanted_skill_obj.desc)
       print('Amount: ', wanted_skill_obj.amount)
       print('am: ', wanted_skill_obj.am)