Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
160
10
中,前置装饰器
@classmethod
指明接下来的函数是类方法。另外,方法的第一个参数是类
本身。
Python
的传统做法是将该参数命名为
cls
,因为
class
是保留关键字,无法用于此
处。下面来为
A
类定义一个类方法,统计由该类创建出了多少个对象实例:
>>> class A():
... count = 0
... def __init__(self):
... A.count += 1
... def exclaim(self):
... print("I'm an A!")
... @classmethod
... def kids(cls):
... print("A has", cls.count, "little objects.")
...
>>>
>>> easy_a = A()
>>> breezy_a = A()
>>> wheezy_a = A()
>>> A.kids()
A has 3 little objects.
注意,我们在
__init__()
中引用的是
A.count
(类特性),而不是
self.count
(对象实例特
性)。在
kids()
方法中,使用的则是
cls.count
,不过也可以写作
A.count
10.6.3
静态方法
第三类方法既不影响类,也不影响类的对象,它出现在类中只是为了方便而已。这就是
态方法
,它使用
@staticmethod
作为前置装饰器,不需要
self
参数或
cls
参数。下面例子
中是一则
CoyoteWeapon
类的广告: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223