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版)
154
10
...
>>> t = Thing()
>>> t.name = "Nyarlathotep"
>>> t.feature = "ichor"
>>> t.age = "eldritch"
>>> t.dump()
{'age': 'eldritch', 'feature': 'ichor', 'name': 'Nyarlathotep'}
10.4
self
正名
Python
被诟病的一点(除了使用空白字符)是需要把
self
作为实例方法的第一个参数
(前面例子中展示过的那种方法)。
Python
使
self
参数查找正确对象的特性和方法。下
面的例子会展示如何调用对象的方法以及
Python
在幕后的实际操作。
还记不记得先前的
Car
类?再次调用
exclaim()
方法。
>>> a_car = Car()
>>> a_car.exclaim()
I'm a Car!
Python
的幕后操作如下:
查找对象
a_car
所属的类(
Car
);
将对象
a_car
作为
self
参数传入
Car
类的
exclaim()
方法。
娱乐一下,你甚至可以像下面这样进行调用,其效果与普通的语法(
a_car.exclaim()
)一样:
>>> Car.exclaim(a_car)
I'm a Car!
但是,我们没理由使用这种冗长的写法。
10.5
特性访问
Python
中,对象特性和方法通常是公开的,你应该约束好自己(这有时也被称为“合意
成年人”政策)。下面来比较一下直接方式和一些替代方法。
10.5.1
直接访问 ...
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