Sometimes it is useful to have a data type similar to the Pascal ``record'' or C ``struct'', bundling together a couple of named data items. An empty class definition will do nicely:
有时类似于Pascal中“记录(record)”或C中“结构(struct)”的数据类型很有用,它将一组已命名的数据项绑定在一起。一个空的类定义可以很好的实现这它:
class Employee: pass john = Employee() # Create an empty employee record # Fill the fields of the record john.name = 'John Doe' john.dept = 'computer lab' john.salary = 1000
A piece of Python code that expects a particular abstract data type can often be passed a class that emulates the methods of that data type instead. For instance, if you have a function that formats some data from a file object, you can define a class with methods read() and readline() that gets the data from a string buffer instead, and pass it as an argument.
某一段 Python 代码需要一个特殊的抽象数据结构的话,通常可以传入一个类,事实上这模仿了该类的方法。例如,如果你有一个用于从文件对象中格式化数据的函数,你可以定义一个带有 read() 和 readline() 方法的类,以此从字符串缓冲读取数据,然后将该类的对象作为参数传入前述的函数。
Instance method objects have attributes, too: m.im_self
is the
object of which the method is an instance, and m.im_func
is the
function object corresponding to the method.
实例方法对象也有属性: m.im_self
是一个实例方法所属的对象,而 m.im_func
是这个方法对应的函数对象。