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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值