小智 84
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,使用Python的内置函数super()(参见Python 2/Python 3文档)可能是一种稍微好一点的调用父进行初始化的方法:
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
Run Code Online (Sandbox Code Playgroud)
或者,与上面完全相同,除了使用零参数形式super(),它只适用于类定义:
class MySubClassBetter(MySuperClass):
def __init__(self):
super().__init__()
Run Code Online (Sandbox Code Playgroud)
ewa*_*all 61
一个英雄的小例子:
class SuperHero(object): #superclass, inherits from default object
def getName(self):
raise NotImplementedError #you want to override this on the child classes
class SuperMan(SuperHero): #subclass, inherits from SuperHero
def getName(self):
return "Clark Kent"
class SuperManII(SuperHero): #another subclass
def getName(self):
return "Clark Kent, Jr."
if __name__ == "__main__":
sm = SuperMan()
print sm.getName()
sm2 = SuperManII()
print sm2.getName()
Run Code Online (Sandbox Code Playgroud)
Bry*_*ley 37
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
Run Code Online (Sandbox Code Playgroud)
wor*_*ad3 15
class Class1(object):
pass
class Class2(Class1):
pass
Run Code Online (Sandbox Code Playgroud)
Class2是Class1的子类
在上面的答案中,super初始化没有任何(关键字)参数.但是,通常情况下,您希望这样做,并传递您自己的一些"自定义"参数.这是一个说明此用例的示例:
class SortedList(list):
def __init__(self, *args, reverse=False, **kwargs):
super().__init__(*args, **kwargs) # Initialize the super class
self.reverse = reverse
self.sort(reverse=self.reverse) # Do additional things with the custom keyword arguments
Run Code Online (Sandbox Code Playgroud)
这是一个子类list,在初始化时,会立即按reverse关键字参数指定的方向排序,如下面的测试所示:
import pytest
def test_1():
assert SortedList([5, 2, 3]) == [2, 3, 5]
def test_2():
SortedList([5, 2, 3], reverse=True) == [5, 3, 2]
def test_3():
with pytest.raises(TypeError):
sorted_list = SortedList([5, 2, 3], True) # This doesn't work because 'reverse' must be passed as a keyword argument
if __name__ == "__main__":
pytest.main([__file__])
Run Code Online (Sandbox Code Playgroud)
感谢传递*args给super,列表可以初始化并填充项目而不是仅为空.(注意,这reverse是根据PEP 3102的仅关键字参数).
| 归档时间: |
|
| 查看次数: |
142895 次 |
| 最近记录: |