Class attributes
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
最新文章
- js三级地区联动
- 移动端web开发总结
- android 中获取视频文件的缩略图(非原创)
- eclipse + marven
- ZOJ 3826
- Php检测文件编码方法
- XBox360-双光盘游戏自制GOD
- lower_bound和upper_bound
- Android:requestWindowFeature应用程序窗体显示状态操作
- How to Set Word Document Properties with C#
- JS 阻止整个网页的内容被选中
- MySQL DATE_FORMAT
- 实验测试之------创建DBlink,查询远端的yang用户下的abcdedfa表,创建同义词
- 【Tesseract】Tesseract API在VS 2013中的配置以及调用
- 安装STS报错(二)
- 搭建Tomcat应用服务器、tomcat虚拟主机及Tomcat多实例部署
- Fiddler使用
- hive 语法 case when 语法
- 【mysql】表备份
- spring cloud: Hystrix(二):简单使用@HystrixCommand的commandProperties配置@HistrixProperty隔离策略
热门文章
- RegisterClientScriptBlock 与 RegisterStartupScript 的区别
- linux 鼠标中键粘帖功能?!!
- ";XX cannot be resolved to a type ";eclipse报错及解决说明
- C# TextBox中只允许输入数字的方法
- ubuntu双网卡bonding配置(转)
- HDU 2087 剪花布条(KMP,不可重叠重复子串)
- 监控系统一些告警方式对比:短信、Email手机端、IM
- qt opencv
- 在Windows 7上安装MongoDB 2.6.7
- Oracle 的简单描述