0

I am new in this website so sorry if I am doing something absurd or against rules but I have a question.

I am new to Python and programming. I am learning Python and when I am exercising I encountered and Error. I searched for solutions here but most of them was above my level that I couldn't understand.

Please try to answer in a way a beginner can understand, thank you.

Here is the code and the Error I get is; 'AttributeError: 'tuple' object has no attribute 'print''

Thanks for any help.

import random


class Enemy:
    name = "Enemy"
    health = 100
    damage = 5
    ammo = 20

    def __init__(self,name,health,damage,ammo):
        self.name = name
        self.health = health
        self.damage = damage
        self.ammo = ammo

    def properties(self):
        print("Properties: ")
        print("Name: ",self.name)
        print("Health: ",self.health)
        print("Damage: ",self.damage)
        print("Ammo: ",self.ammo)

    def attack(self):
        print(self.name + " is attacking!")
        ammo_spent = random.randrange(1,10)
        print(str(ammo_spent) + " ammo spent.")
        self.ammo -= ammo_spent
        return (ammo_spent,self.damage)

    def getattacked(self,ammo_spent,damage):
        print ("I've been shot!")
        self.health -= (ammo_spent * damage)

    def is_ammo_depleted(self):
        if (self.ammo <= 0):
            print (self.name + "'s ammo depleted.")
            return True
        return False
    def check(self):
        if (self.health <= 0):
            print("YOU DIED.")




Enemies = []

i = 0
while (i < 9):
    randomhealth = random.randrange(125,300,25)
    randomdamage = random.randrange(25,100,25)
    randomammo = random.randrange(20,200,20)
    new_enemy = ("Enemy" + str(i+1),randomhealth,randomdamage,randomammo)
    Enemies.append(new_enemy)

    i += 1

for Enemy in Enemies:
    Enemy.properties()
5
  • 1
    As the error message says, the Enemy class has no method print. If you want to be able to call .print() on an Enemy instance, you have to define a print() method. Commented Feb 18, 2019 at 22:04
  • replace Enemy.print() by Enemy.properties() ... or do a __str__(self): method and do print(Enemy) Commented Feb 18, 2019 at 22:06
  • I tried Enemy.properties() before but I got the same error just properties instead of print. Where should I insert the __str__(self)? Commented Feb 18, 2019 at 22:10
  • stackoverflow.com/questions/7152312/python-str-for-an-object - you return a string from it Commented Feb 18, 2019 at 22:23
  • 1
    You are not creating enmies _ you are creating tuples. Commented Feb 18, 2019 at 22:24

2 Answers 2

2

You need to create instances of your class:

Enemies = []

i = 0
while (i < 9):
    randomhealth = random.randrange(125,300,25)
    randomdamage = random.randrange(25,100,25)
    randomammo = random.randrange(20,200,20)

    # create an Enemy - not a tuple of values
    new_enemy = Enemy( "Enemy {}".format(i), randomhealth, randomdamage, randomammo)
    Enemies.append(new_enemy)

    i += 1

for Enemy in Enemies:
    Enemy.properties()

If you create a __str__(self) method in your class you can "tell" python how to print an instance of your class:

class Enemy:
    # snipped what you already had

    # is used if you print(instance)
    def __str__(self):
        return  """Properties:
Name: {}
Health: {}
Damage: {}
Ammo:   {}""".format(self.name, self.health, self.damage, self.ammo)

    # is used by lists if you print a whole list
    def __repr__(self):
        return str(self)

Read about __str__ here: python __str__ for an object

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your help. I forgot to type Enemy before () and after new_enemy. This solved my problem.
0

Okay, first off, don't do shenanigans like

i = 0
while (i < 9):
    i++
    // bad

use

for i in range(9):
   // good

instead.

Second off, with

new_enemy = ("Enemy" + str(i+1),randomhealth,randomdamage,randomammo)
Enemies.append(new_enemy)

you're appending a Tuple to your Entities list. How could you possibly expect that Tuple to have the properties of your Entity class?

So what you want to use instead is

Enemies = []

for i in range(9):
    randomhealth = random.randrange(125,300,25)
    randomdamage = random.randrange(25,100,25)
    randomammo = random.randrange(20,200,20)
    new_enemy = Enemy("Enemy" + str(i+1), randomhealth, randomdamage, randomammo)
    Enemies.append(new_enemy)

for Enemy in Enemies:
    Enemy.print()

Next, in your last for loop, you're using the class name Enemy as a variable in the loop. Terrible idea, but luckily you can just make that lowercase. So, why does it STILL say that your Enemy class has no print member? Because you haven't defined one, you called the method "properties" instead.

for enemy in Enemies:
    enemy.properties()

And it works. However, since we're in python, we can simplify this code quite a lot.

Endresult:

import random


class Enemy:

    def __init__(self,name,health,damage,ammo):
        self.name = name
        self.health = health
        self.damage = damage
        self.ammo = ammo

    def __str__(self):
        return "Properties:\nName: {}\nHealth: {}\nDamage: {}\nAmmo: {}".format(
            self.name, self.health, self.damage, self.ammo)

    #your other methods

Enemies = [Enemy(name="Enemy" + str(i),
                 health=random.randrange(125, 300, 25),
                 damage=random.randrange(25, 100, 25),
                 ammo=random.randrange(20, 200, 20))
           for i in range(1, 10)]

for enemy in Enemies:
    print(enemy)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.