UnMarkedTrailer UnMarkedTrailer - 1 year ago 95
Python Question

AttributeError: 'str' object has no attribute '_Animal__animal_available'

I am working on an assignment for class, and get the following AttributeError:

File "C:\Users\***\Desktop\Python\******PetStore\Animal.py", line 24, in get_available
self.__animal_available = 'available'
AttributeError: 'str' object has no attribute '_Animal__animal_available'

The assignment is to create program simulating a Pet Store. The program has to create animal with a name, and whether it is available. Whenever after setting the animal available I get the error above. Here is a snippet of the main program.

elif menu_input == '1':
type = input("What type of animal would you like to create? ")
name = input("What is the animal’s name? ")
available = input('Is the animal available for adoption y/n? ')
Animal.Animal.get_available(available, available)

Now here is the Animal class where the error is thrown.

import random

class Animal:

def __init__(self, animal_type, animal_name, available):
self.__animal_name = animal_name
self.__animal_type = animal_type

def get_animal_type(self):
return self.__animal_type

def get_name(self):
return self.__animal_name

def check_mood(self):
return self.__mood

def get_available(self, available):
if available != 'y':
self.__animal_available = 'not available'
self.__animal_available = 'available'
return self.__animal_available

def set_mood(self):
random_number = random.randint(1,3)
if(1 == random_number):
self.__mood = "happy"
if(2 == random_number):
self.__mood = "hungry"
if(3 == random_number):
self.__mood = "sleepy"

Answer Source

You need to create an instance of Animal and then call the get_available method on that. e.g.:

animal_instance = Animal.Animal(type, name, available)

Of course, you can do this without the intermediate variable to hold the instance:

print(Animal.Animal(type, name, available).get_available())

What you're doing is calling the method as if it were a static method. Since you pass available twice, you're basically setting self inside the method to available (which is a string) and that explains the error that you're seeing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download