<<DEITEL - Python How to Program 2002>>Special attributes of an obje
时间:2010-08-24 来源:菜刀大侠
Attribute Description
__class__ A reference to the class from which the object was instantiated.
__dict__ A dictionary that corresponds to the object’s namespace. Each keyvalue pair represents an identifier and its value in the namespace.
代码
1 # Fig. 7.1: Time1.py
2 # Simple definition of class Time.
3
4 class Time:
5 """Time abstract data type (ADT) definition"""
6
7 def __init__( self ):
8 """Initializes hour, minute and second to zero"""
9
10 self.hour = 0 # 0-23
11 self.minute = 0 # 0-59
12 self.second = 0 # 0-59
13
14 def printMilitary( self ):
15 """Prints object of class Time in military format"""
16
17 print "%.2d:%.2d:%.2d" % ( self.hour, self.minute, self.second )
18
19 def printStandard( self ):
20 """Prints object of class Time in standard format"""
21
22 standardTime = ""
23
24 if self.hour == 0 or self.hour == 12:
25 standardTime += "12:"
26 else:
27 standardTime += "%d:" % ( self.hour % 12 )
28
29 standardTime += "%.2d:%.2d" % ( self.minute, self.second )
30
31 if self.hour < 12:
32 standardTime += " AM"
33 else:
34 standardTime += " PM"
35
36 print standardTime,
37
38 ##########################################################################
39 # (C) Copyright 2002 by Deitel & Associates, Inc. and Prentice Hall. #
40 # All Rights Reserved. #
41 # #
42 # DISCLAIMER: The authors and publisher of this book have used their #
43 # best efforts in preparing the book. These efforts include the #
44 # development, research, and testing of the theories and programs #
45 # to determine their effectiveness. The authors and publisher make #
46 # no warranty of any kind, expressed or implied, with regard to these #
47 # programs or to the documentation contained in these books. The authors #
48 # and publisher shall not be liable in any event for incidental or #
49 # consequential damages in connection with, or arising out of, the #
50 # furnishing, performance, or use of these programs. #
51 ##########################################################################
52
Time1.Time
>>> print time1.__dict__
{'second': 0, 'minute': 0, 'hour': 0}
>>> print time1.doc
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Time instance has no attribute 'doc'
>>> print time1.__doc__
Time abstract data type (ADT) definition
>>> print time1.__module__
Time1
>>>
相关阅读 更多 +