内置函数¶
abs()¶
all()¶
any()¶
ascii()¶
bin()¶
bool()¶
bytearray()¶
bytes()¶
callable()¶
chr()¶
classmethod()¶
compile()¶
complex()¶
delattr()¶
dict()¶
dir()¶
divmod()¶
enumerate()¶
eval()¶
exec()¶
filter()¶
float()¶
format()¶
frozenset()¶
getattr()¶
globals()¶
hasattr()¶
hash()¶
help()¶
hex()¶
id()¶
input()¶
int()¶
isinstance()¶
issubclass()¶
iter()¶
len()¶
list()¶
locals()¶
map()¶
max()¶
memoryview()¶
min()¶
next()¶
object()¶
oct()¶
open()¶
ord()¶
pow()¶
print()¶
property()¶
range()¶
repr()¶
reversed()¶
round()¶
set()¶
setattr()¶
slice()¶
sorted()¶
staticmethod()¶
str()¶
sum()¶
super()¶
tuple()¶
type()¶
vars()¶
zip()¶
__import__()¶
super()¶
super()
内建方法,会返回一个代理对象(superclass 的临时对象),它允许我们访问基类(base class)的方法
在 Python 中,super()
主要有两种用途:
- 允许我们避免显式使用基类名称
- 使用多重继承
pass
pass
super()
with Single Inheritance: 使用 super()
来 refer base class
class Mammal(object):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
super().__init__('Dog')
d1 = Dog()
Result 1
此处,是从 Dog
类中,直接调用了 Mammal
类的 __init__
方法,即 super().__init__('Dog')
,而非是 Mammal.__init__(self, 'Dog')
由于我们在调用其成员时不需要指定基类的名称,因此如果需要的话,我们可以轻松更改基类名称。
The super()
builtin returns a proxy object, a substitute object that can call methods of the base class via delegation. This is called indirection (ability to reference base object with super()
)
Since the indirection is computed at the runtime, we can use different base classes at different times (if we need to).
super()
with Multiple Inheritance
class Animal:
def __init__(self, Animal):
print(Animal, 'is an animal.');
class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammal):
def __init__(self, NonWingedMammal):
print(NonWingedMammal, "can't fly.")
super().__init__(NonWingedMammal)
class NonMarineMammal(Mammal):
def __init__(self, NonMarineMammal):
print(NonMarineMammal, "can't swim.")
super().__init__(NonMarineMammal)
class Dog(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Dog has 4 legs.');
super().__init__('Dog')
d = Dog()
print('')
bat = NonMarineMammal('Bat')
Result 2
Method Resolution Order (MRO)
Method Resolution Order (MRO) 是指在存在多重继承的情况下,应该继承方法的顺序。可以使用 __mro__
属性查看 MRO。
MRO如何运作:
- 派生调用中的方法总是在基类的方法之前调用。即 Dog 类在 NonMarineMammal 或 NoneWingedMammal 之前被调用。这两个类在 Mammal 之前被调用,Mammal 类在 Aninal 类之前被调用。而 Aninal 类则在 object 之前被调用;
- 如果有多个像 Dog(NonMarineMammal, NonWingedMammal) 这样的 parents,则首先调用 NonMarineMammal 的方法,因为它首先出现。
Result 3