In order to print Card objects in a way that people can easily read, we need a mapping from the integer codes to the corresponding ranks and suits. A natural way to do that is with lists of strings.

class Card:
""" represents a standard playing card.
class attributes: suit_names, rank_names
instance attributes: suit, rank """ suit_names = ['Clubs','Diamonds','Hearts','Spades']
rank_names = [None,'Ace','','','','','','',
'','','','Jack','Queen','King'] def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank def __str__(self):
return '%s of %s' % (Card.suit_names[self.suit],
Card.rank_names[self.rank])

Because suit_names and rank_names are defined outside of any method, they are class attributes; that is, they are associated with the class Card rather than with a particular Card instance. Attributes like suit and rank are more precisely called instance attributes because they are associated with a particular instance. Both kinds of attributes are accessed using dot notation. For example, in __str__, self is a Card object, and self.rank is its rank. Similarly, Card is a class object, and Card.rank_names is a list of strings associated with the class. Every card has its own suit and rank, but there is only one copy of suit_names and rank_names.

Finally, the expression Card.rank_names[self.rank] means ‘use the attribute rank from the object self as an index into the list rank_names from the class Card, and select the appropriate string’.

The first element of rank_names is None because there is no card with rank zero. By including None as a place-keeper, we get a mapping with the nice property that index 2 maps to the string ‘2’, and so on.

Here is a diagram that shows the Card class object and one Card instance:

from Thinking in Python

最新文章

  1. js三级地区联动
  2. 移动端web开发总结
  3. android 中获取视频文件的缩略图(非原创)
  4. eclipse + marven
  5. ZOJ 3826
  6. Php检测文件编码方法
  7. XBox360-双光盘游戏自制GOD
  8. lower_bound和upper_bound
  9. Android:requestWindowFeature应用程序窗体显示状态操作
  10. How to Set Word Document Properties with C#
  11. JS 阻止整个网页的内容被选中
  12. MySQL DATE_FORMAT
  13. 实验测试之------创建DBlink,查询远端的yang用户下的abcdedfa表,创建同义词
  14. 【Tesseract】Tesseract API在VS 2013中的配置以及调用
  15. 安装STS报错(二)
  16. 搭建Tomcat应用服务器、tomcat虚拟主机及Tomcat多实例部署
  17. Fiddler使用
  18. hive 语法 case when 语法
  19. 【mysql】表备份
  20. spring cloud: Hystrix(二):简单使用@HystrixCommand的commandProperties配置@HistrixProperty隔离策略

热门文章

  1. RegisterClientScriptBlock 与 RegisterStartupScript 的区别
  2. linux 鼠标中键粘帖功能?!!
  3. "XX cannot be resolved to a type "eclipse报错及解决说明
  4. C# TextBox中只允许输入数字的方法
  5. ubuntu双网卡bonding配置(转)
  6. HDU 2087 剪花布条(KMP,不可重叠重复子串)
  7. 监控系统一些告警方式对比:短信、Email手机端、IM
  8. qt opencv
  9. 在Windows 7上安装MongoDB 2.6.7
  10. Oracle 的简单描述