Static and Class Methods

As of Python 2.2, it is possible to define two kinds of methods within a class that can be called without an instance: static methods work roughly like simple instance-less functions inside a class, and class methods are passed a class instead of an instance. Although this feature was added in conjunction with the new-style classes discussed in the prior sections, static and class methods work for classic classes too.

To enable these method modes, special built-in functions called staticmethod and classmethod must be called within the class, or invoked with the decoration syntax we’ll meet later in this chapter. In Python 3.0, instance-less methods called only through a class name do not require a staticmethod declaration, but such methods called through instances do.

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元