在Python中,你如何从超子类?
Answer 1:
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
或者,甚至更好,使用Python的内置功能, super()
(见Python的2 / Python 3中为它的文档)可能会要求初始化父的稍微好一点的方法:
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
或者,上面刚刚同样的事情,不同的是使用零参数的形式super()
它只能在类定义中:
class MySubClassBetter(MySuperClass):
def __init__(self):
super().__init__()
Answer 2:
英勇的小例子:
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()
Answer 3:
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
在继承部分 Python文档中解释比较详细
Answer 4:
class Class1(object):
pass
class Class2(Class1):
pass
等级2是一个子类的Class1的
Answer 5:
在上面的答案,该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
这是的一个子类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__])
得益于传递的*args
到super
,列表可以初始化和项目,而不是只为空填充。 (请注意, reverse
是按照只有关键字的参数PEP 3102 )。
Answer 6:
还有一种办法,使在Python子类动态与函数type()
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__()
通常你想使用元类时使用此方法。 当你想要做一些较低级别的自动化,即改变了蟒蛇的方式是如何创建类。 最有可能你永远不会需要做的是这样,但是当你这样做,比你已经知道你在做什么。
Answer 7:
class Subclass (SuperClass):
# Subclass stuff here
Answer 8:
你用:
class DerivedClassName(BaseClassName):
有关详细信息,请参见Python文档,第9.5节 。
Answer 9:
class Mammal(object):
#mammal stuff
class Dog(Mammal):
#doggie stuff
Answer 10:
class BankAccount:
def __init__(self, balance=0):
self.balance = int(balance)
def checkBalance(self): ## Checking opening balance....
return self.balance
def deposit(self, deposit_amount=1000): ## takes in cash deposit amount and updates the balance accordingly.
self.deposit_amount = deposit_amount
self.balance += deposit_amount
return self.balance
def withdraw(self, withdraw_amount=500): ## takes in cash withdrawal amount and updates the balance accordingly
if self.balance < withdraw_amount: ## if amount is greater than balance return `"invalid transaction"`
return 'invalid transaction'
else:
self.balance -= withdraw_amount
return self.balance
class MinimumBalanceAccount(BankAccount): #subclass MinimumBalanceAccount of the BankAccount class
def __init__(self,balance=0, minimum_balance=500):
BankAccount.__init__(self, balance=0)
self.minimum_balance = minimum_balance
self.balance = balance - minimum_balance
#print "Subclass MinimumBalanceAccount of the BankAccount class created!"
def MinimumBalance(self):
return self.minimum_balance
c = BankAccount()
print(c.deposit(50))
print(c.withdraw(10))
b = MinimumBalanceAccount(100, 50)
print(b.deposit(50))
print(b.withdraw(10))
print(b.MinimumBalance())
Answer 11:
子类在Python是做如下:
class WindowElement:
def print(self):
pass
class Button(WindowElement):
def print(self):
pass
这里是一个教程关于Python也含有类和子类。
文章来源: Python: How do I make a subclass from a superclass?