1. 程式人生 > >python39、40 模組、類和物件

python39、40 模組、類和物件

#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
類: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()