0
\$\begingroup\$

I am practicing classes and subclasses in Python. I'm not sure whether it might be useful to add a subclass to the following code, instead of just adding methods to the class.

# Practice with classes
class ElixerTroops(object):
    def __init__(self, name, dps, life, special):
        self.name = name
        self.dps = dps
        self.life = life
        self.special = special
barbarian = ElixerTroops("barbarian ", 23.00 , 95.0, "none")
archer    = ElixerTroops("archer    ", 20.00 , 40.0, "shoots arrows")
dragon    = ElixerTroops("dragon   ", 180.0 , 2300, "flies")

print "Troop: " + barbarian.name
print "Damage: " + str(barbarian.dps)
print "Life: " + str(barbarian.life)
print "Special Abilities: " + barbarian.special

troops = [barbarian, archer]
troops.append(dragon)
for i in troops:
    print "Name:", i.name, "Damage:", i.dps, "Life:", i.life, "Special Abilities:", i.special

Could I have made this code simpler to read?

\$\endgroup\$
2
  • 5
    \$\begingroup\$ Welcome to Code Review! I've removed the noise and off-topic questions from your post, but I'll leave it up to you to come up with a better title and edit it so that it tells reviewers what your code is doing - rule of thumb on this site, if your question title is worded like a question, something is wrong. The watermark says "state the task that your code accomplishes; make it distinctive." \$\endgroup\$ Commented Jun 9, 2016 at 20:58
  • \$\begingroup\$ Relevant read: programmers.stackexchange.com/q/65179/68834 \$\endgroup\$ Commented Jun 9, 2016 at 21:28

1 Answer 1

3
\$\begingroup\$

Class inheritance is really useful. For example, if you had a class that was just Troops, you would add all the functions you want all troops in the game to have. Then you decide that some functions (or abilities) you don't want all troops to have, so you make a new class: ElixerTroops(Troops) This allows you to have all the functions the class Troops has, but also add new functions without affecting the original Troops class.

As for your code, it's pretty good, just one thing, instead of saying:

for i in troops:

It's better to say:

for troop in troops:

This makes it easier to read and understand

Also, instead of printing each self value, you could make a function in the class called:

def __str__(self):
    return "Name {}, Damage: {}, Life {}, Special Abilities {} ".format(self.name, self.dps, self.life, self.special)

This allows you to simply call barbarian (not calling any function) and getting the string from the function str

print barbarian
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.