#create a mapping of state to abbrevuation
states = {
 'Oregon': 'OR',
 'Florida': 'FL',
 'California': 'CA',
 'New York': 'NY',
 'Michigan': 'MI'
}
#create a basic set of states and some cities in them
cities = {
 'CA': 'San Francisco',
 'MI': 'Detroit',
 'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' * 20
print "NY state has:", cities['NY']
print "OR state has:", cities['OR']
#print some states
print '-' * 20
print "Michigan's abbrevuation is :", states['Michigan']
print "Florida's abbrevuation is :", states['Florida']
#do it by using the state then cities dict
print '-' * 20
print "Michigan hsa:", cities[states['Michigan']]
print "Florida has:", cities[states['Florida']]
#print every state abbrevuation
print '-' * 20
print "States:", states.items(),"\n"
for state, abbrev in states.items():
 print "%s is abbrevuation %s" % (state, abbrev)
 
# print every city in state
print '-' * 20
for abbrev, city in cities.items():
 print "%s has the city %s" % (abbrev, city)
 
#now do both at the same time
print '-' * 20
for state, abbrev in states.items():
 print "%s states is  abbrevuated %s and has city %s" % (
 state, abbrev, cities[abbrev])
 
print '-' * 20
#safely get a abbrevuation by state that might not be there
state = states.get('Texas', None)
if not state:
 print "sorry, no Texas."
 
#get a city with a default values
city = cities.get('TX', 'Does not Exist')
print "the city for the state 'TX' is: %s" % city
python39、40 模块、类和对象
类:
class Song(object):
 
 def __init__(self, lyrics):
  self.lyrics = lyrics
  
 def sing_me_a_song(self):
  for line in self.lyrics:
   print line
  print self
happy_bday = Song(["Happy birethday to you",
     "I don't want to get sued",
     "So I'll stop right there"])
     
bulls_on_parade = Song(["They rally around the family",
      "With pockets full of shells",
      "Oh, you are good!",
      "I ger more than you!",
      "hhha"])
      
      
song_list = ["They rally around the family",
    "With pockets full of shells",
    "Oh, you are good!",
    "I ger more than you!",
    "hhha"]
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
text = Song(song_list)
text.sing_me_a_song()
python39、40 模块、类和对象

相关文章:

  • 2021-08-29
  • 2021-11-30
  • 2022-01-23
  • 2021-06-16
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-30
  • 2021-05-27
相关资源
相似解决方案