Type Object '... ' has no attribute name '... ' - python

I keep on getting the no attribute error in python. I want to make a class for cities to put into a program I am writing (Im trying to learn python on the side while working). I basically want to be able to put data into a class for cities and use that in another place. I guess, I would need to know how to access attributes from a class. Im probably doing a bunch wrong so any feedback would be helpful
class City:
def __init__(self, name, country, re_growth10):
self.name = name #name of the city
self.country = country #country the city is in
self.re_growth10 = re_growth10 #City Real estate price growth over the last 10 years
def city_Info(self):
return '{}, {}, {}'.format(self.name, self.country, self.re_growth10)
Toronto = City("Toronto", "Canada", 0.03) #Instance of CITY
Montreal = City("Montreal", "Canada", 0.015) #Instance of CITY
user_CityName = str(input("What City do you want to buy a house in?")) #user input for city
def city_Compare(user_CityName): #Compare user input to instances of the class
cities = [Toronto, Montreal]
for City in cities:
if City.name == user_CityName:
print(City.name)
else:
print("We Don't have information for this city")
return ""
print(City.name)

You are getting confused because you have a variable that has the same name as your class, City. To avoid this, use lower-case names for variables. Once you change this, you get a different error:
NameError: name 'city' is not defined
The reason is that you are trying to print the name of a variable which is defined inside a function, but the print statement is outside the function. To fix this, put your last print statement inside the function city_Compare, and call that function (which you never do).
Or change the function to return an object instead of printing it:
def find_city(name):
cities = [Toronto, Montreal]
for city in cities:
if city.name == name:
return city
return None
city_name = input("What City do you want to buy a house in?")
city = find_city(city_name)
if city is not None:
print(city.name)
else:
print("We Don't have information for this city")

Related

Stored Class instance objects in dictionary. How do I get them out?

Context: I'm in a Programming Concepts course. the assignment is to define a Person class, a Customer subclass.
Write a class named Person with data attributes for a person’s name, address, and telephone number. Next, write a class named Customer that is a subclass of the Person class. The Customer class should have a data attribute for a customer number and a Boolean data attribute indicating whether the customer wishes to be on a mailing list. Demonstrate an instance of the Customer class in a simple program.
I have been able to:
Create class and subclass
Get user input to define customer name, number, address, phone and yes/no for mailer
Create instance of the Customer class object as CurrentCustomer
Store that class object as a value in a Customers dictionary, using CustomerNumber as the key.
Where I am having trouble:
Getting the object instance back from the dictionary, and using it to display the customers' data one by one. basically for key in Customers, print the values for Customer class object CurrentCustomer
example: a header that reads:
Customer Number -- Name -- Address -- Phone -- Mailing List?
then:
Customer 1 -- John Smith - 123 Easy Street Smalltown, ST -- (555) 123 -1234 -- True
The way the instructor has outlined setting up the classes is as follows:
Define the Person class.
class Person:
def __init__(self,name,address,phone):
self.__name = name
self.__address = address
self.__phone = phone
**Write mutators for the attributes.**
def set_name(self,name):
self.__name = name
def set_address(self, address):
self.__address = address
def set_phone(self, phone):
self.__phone = phone
# Write accessors for the attributes.
def get_name(self):
return self.__name
def get_address(self):
return self.__address
def get_phone(self):
return self.__phone
Define the Customers subclass.
class Customer(Person):
# Initialize the Customer class object
def __init__(self, name, address, phone, customer_number, mailing_list):
# Call Person class init method.
Person.__init__(self, name, address, phone)
# Initialize Customer class specific attributes.
self.__customer_number = customer_number
self.__mailing_list = mailing_list
# Write mutators for Customer class attributes
def set_customer_number(self, customer_number):
self.__customer_number = customer_number
def set_mailing_list(self, mailing_list):
self.__mailing_list = mailing_list
# Write Accessors for Customer class attributes.
def get_customer_number(self):
return self.__customer_number
def get_mailing_list(self):
return self.__mailing_list
Here is how I have the main function set up currently to get customer information and store the object in thedictionary:
Define main function.
def main():
# Initialize empty list to store customer numbers.
CustomerNumbers = []
# initialize empty dictionary to store Customer class instances.
Customers = {}
# Greet user.
print("Hello. Let's enter our customer records.\n")
# Get number of customers.
NumCustomers = get_num_customers()
if NumCustomers > 1:
print("\nGot it! We will be entering " + str(NumCustomers) +" customers.")
else:
print("\nGot it! We are entering " + str(NumCustomers) +" customer.")
# Fill list of customer numbers
for Count in range (1, NumCustomers+1):
CustomerNumbers.append('Customer Number ' + str(Count))
# Store each customer's data into a dictionary with Customer Number as the Key
for i in CustomerNumbers:
CustomerNumber = i
CurrentCustomer = CustomerNumber
Name, Address, Phone, Mailing_List = get_customer_info(CurrentCustomer)
CustomerData = Customer(Name, Address, Phone, CustomerNumber, Mailing_List)
Customers[CurrentCustomer] = CustomerData
print(Name +"'s information saved.")
print("\n\t\t Customer Data ")
print("\t\t===============")
print("\nCustomer Name\t\tCustomer Number\t\tAddress\t\tPhone Number\tMailing List?\n")
Currently using, but have tried several different ways to get the Class object back:
for key, in Customers:
print(Customer.get_name())
Output
Customer Data
===============
Customer Name Customer Number Address Phone Number Mailing List?
Traceback (most recent call last):
File "G:/My Drive/Personal/Fall 2021/COP 2510 - Concepts of Programming/Chapter 11/Clark_J_Chapter_11_Assignment_3.py", line 243, in <module>
main()
File "G:/My Drive/Personal/Fall 2021/COP 2510 - Concepts of Programming/Chapter 11/Clark_J_Chapter_11_Assignment_3.py", line 109, in main
for key, in Customers:
ValueError: too many values to unpack (expected 1)

How to print specific value from specific key from JSON in Python

I wrote 2 functions so I can get champion ID knowing champion Name but then I wanted to get champion Name knowing champion ID but I cannot figure it out how to extract the name because of how the data structured.
"data":{"Aatrox":{"version":"8.23.1","id":"Aatrox","key":"266","name":"Aatrox"
so in my code I wrote ['data']['championName'(in this case Aatrox)]['key'] to get the champion ID/key. But how can I reverse it if for example I don't know the champion Name but champions ID. How can I get the champion Name if after writing ['data'] I need to write champion Name so I can go deeper and get all the champions info like ID, title etc..
link: http://ddragon.leagueoflegends.com/cdn/8.23.1/data/en_US/champion.json
Code:
def requestChampionData(championName):
name = championName.lower()
name = name.title()
URL = "http://ddragon.leagueoflegends.com/cdn/8.23.1/data/en_US/champion/" + name + ".json"
response = requests.get(URL)
return response.json()
def championID(championName):
championData = requestChampionData(championName)
championID = str(championData['data'][championName]['key'])
return championID
since python values are passed by reference you can make a new dict with keys as the champion id pointing to the values of the previous dict, that way you dont duplicate too much data. but be carefull if you change data in one dict the data will be changed in the other one too
def new_dict(d):
return { val["id"]:val for val in d.values() }
I solved my problem with this code:
def championNameByID(id):
championData = requestChampionData()
allChampions = championData['data']
for champion in allChampions:
if id == allChampions[champion]['key']:
championName = allChampions[champion]['name']
return championName

Python sort a dictionary that has objects in it's values by alphabetical order of one of it's attributes

so I'm making an agenda.
The attribute of agenda that manages the dictionary is : self.ContactList = {}
Inside this I have the telephone number as key for a contact (which is a class).
The Contact class has an attribute called telephone and other ones including the contact name.
I want a function that lists the contacts in the agenda, however I wanna list them by alphabetical order of the Contacts it contains.
Right now I'm using this to print the contacts (already have overriden the ____str____ of the contact class to allow this):
def listcontacts(self, agenda):
print("Contact List\n")
for tel, contact in agenda.ContactList.items():
print(contact,"\n"*2)
How to sort self.ContactList by the contact's attribute "name"?
EDIT: The contact class is as follows
class Contact:
def __init__(self, name, adress, zipcode, telephone):
self.name = name
self.adress = adress
self.zipcode = zipcode
self.telephone = telephone
def __str__(self):
return ( "Name: " + self.name + "\nAdress: " + self.adress + "\nZipCode: " + self.zipcode
+ "\nTelephone: " + self.telephone)
If you want to sort a list, use the sorted() function. If you want the sort to use an interesting ordering criterion, use the key= keyword:
for tel, contact in sorted(agenda.ContactList.items(), key=lambda x: x[1].name):

How to created inherited objects using Python?

I have the following nested dict:
world = {'europe' :
{'france' : ['paris', 'lion'],
'uk' : ['london', 'manchester']}},
{'asia' :
{'china' : ['beijing'],
{'japan' : ['tokyo']}}
I'm trying the following objects out of it:
class world:
continents = {} # dict of continents
class continent(world):
name = '' # name of the continent
countries = {} # dict of countries
class country(continent):
name = '' # name of the country
cities = [] # list of cities
class city(country):
name = '' # name of the city
The goal is to get all countries from the continent object and alternatively to get the country and the continent names from a city object.
What is the best way to do so in Python?
Inheriting from "higher" classes is incorrect here. If you inherit a class, that inheriting class is the parent class plus more. You're saying here that country is a continent and also is a world. That is clearly not true and unnecessary.
There is no necessary hierarchical relationship between those four classes. Worlds are worlds, continents are continents, countries are countries and cities are cities. It's enough for continents to contain a list of the countries they hold, or conversely for a country to hold a reference to the continent it's in. The classes themselves do not need a hierarchical relationship.
Consider also whether such a strict 1:1 relationship is useful. There are countries which exist on more than one continent, depending on how exactly you want to define these terms (colonies are fun). How to design this data structure really depends on the concrete goal you have for it.
Syntactically, the classes should be defined as
class World(object):
def __init__(self, continents):
self.continents = continents
class Continent(World):
def __init__(self, name):
self.name = '' # name of the continent
...
class Country(Continent):
def __init__(self, name):
self.name = '' # name of the country
...
class City(Country):
def __init__(self, name):
self.name = '' # name of the city
...
However, in this case it does not make any sense.
Subclassing means something else:
Class Animal(object):
pass
Class Dog(Animal):
pass
Class Snake(Animal):
pass
A dog is a specific type of animal. A dog is an animal. A snake is also an animal.
In your case, a Continent is not a type of World, a Country is not a type of Continent and so on.
Instead you want to relate those classes, which can live as separate classes or they can go one inside the other.
For example
class City(object):
def __init__(self, name):
self.name = '' # name of the city
class Country(object, cities):
def __init__(self, name, cities):
self.name = name # name of the country
self.cities = cities # it's a list of Cities instances
class Continent(object):
def __init__(self, name, countries):
self.name = name # name of the continent
self.countries = countries # it's a list of Countries instances
class World(object):
def __init__(self, continents):
self.continents = continents # it's a list of Continent instances
france = Country('France', [City('Paris'), City('Annecy'), City('St. Tropez')])
italy = Country('Italy', [City('Rome'), City('Milan')])
uk = Country('UK', [City('London'), City('Bath')])
europe = Continent('europe', [france, italy, uk])
...
Note: the above is just an example. It may not be the best way to do it in python for a number of reasons, depending on how you intend to manipulate the objects.
It's a wide and long subject.
I suggest to look online for a good tutorial about Object Orientation (also called OOP for Object Oriented Programming or OOD for Object Oriented Design).
Here is one tutorial, but there are thousands available online.
After that, you will be able to design the interfaces your objects should expose in order to offer a certain functionality at the local/application level.
Tip: using a RDBM (Relational Data Base Management System), would help you relating and managing the models. Learn about ERD's (Entity-Relationship Diagrams) to help you design your data model.
:)

How do I get StructuredProperty's in Google App Engine to update?

I have a Player model that is assigned to a Team. When I assign them to a Team I see the correct team name show up when I access player.team.name. If I go to the Team and rename it, the player.team.name still returns the old team name.
A player is assigned to "New Orleans Hornets". The player.team.name is "New Orleans Hornets".
Rename "New Orleans Hornets" team to "New Orleans Pelicans". The player.team.name is still "New Orleans Hornets".
Code:
class Team(ndb.Model):
name = ndb.StringProperty()
class Player(ndb.Model):
name = ndb.StringProperty()
team = ndb.StructuredProperty(Team)
I have a feeling I need to use a KeyProperty here but can't figure out how that would work. Any help is appreciated.
The StructuredProperty stores the Team entity within the Player entity (ie.It has a copy of the team). So you would need to find each Player who is a member of the team and updated the Player.team entry with the new name.
Using a KeyProperty will store a reference to the Team entity. When retrieving a Player, you will need to do a separate get call to retrieve the associated Team.
The model will look something like:
class Team(ndb.Model):
name = ndb.StringProperty()
class Player(ndb.Model):
name = ndb.StringProperty()
team = ndb.KeyProperty(kind=Team)
To store a Player with a team:
team = #look up an existing team entity
player = Player()
player.name = "Joe"
player.team = team.key()
player.put()
To retrieve a Player with their team name you would:
player = ....
players_team = Team.get_by_id(player.team)
players_team.name # to access the name

Categories

Resources