在Python中,如何从超类创建子类?
注意,python改变了子类化的方式,所以有两种方法可以实现,而且它们不混合。如果你混用,你会出错的。阅读这篇文章可以看到不同之处:stackoverflow.com/questions/1713038/…
# 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__()
另外,有些人警告不要使用super,特别是对于新的python程序员(如lutz)。我避开它。
避免使用super的唯一原因是,如果您不了解super在python中的工作方式与super/parent在其他语言中的工作方式之间的差异。诚然,对于来自其他语言的人来说,这并不明显,但我不会得出这样的结论,即它是一种值得"小心"的东西。它确实有效。只是工作方式不同而已。在抱怨得到出乎意料的结果之前,先阅读一下它在Python中的实际作用。
这两者有什么区别?
这是两种调用超类函数的方法之间的区别
一个英雄的小例子:
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()
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
#
python文档中关于继承的部分更详细地解释了它。
如果要添加更多的代码,只需定义__init__方法,否则仍然使用原始init方法(尽管值得一提,并且是完全有效的代码)
我认为这个问题很模糊,足以假设可能会添加更多的代码。提供过多的信息总比不提供足够的信息好,当OP实现它时,最后会出现另一个问题。:)
class Class1(object):
pass
class Class2(Class1):
pass
第2类是第1类的一个子类
酷。这就是我实际上在寻找的,也就是说,一个没有对super进行扩展/重写的子类。
在上面的答案中,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,列表可以初始化和填充项目,而不只是空的。(注意,根据PEP 3102,reverse是一个只包含关键字的参数)。
还有另一种方法可以使用函数type()在python中动态生成子类:
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__()
在处理元类时,通常要使用此方法。当您想要执行一些较低级别的自动化时,这会改变Python创建类的方式。很可能你不需要这样做,但是当你这样做的时候,你已经知道你在做什么了。
您使用:
class DerivedClassName(BaseClassName):
有关详细信息,请参见第9.5节的python文档。
class Subclass (SuperClass):
# Subclass stuff here
class Mammal(object):
#mammal stuff
class Dog(Mammal):
#doggie stuff
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())
如果你能解释一下它的作用,这个答案会更有帮助。
尽管此代码可能有助于解决问题,但它不能解释为什么和/或如何回答问题。提供这种额外的背景将显著提高其长期教育价值。请编辑您的答案以添加解释,包括哪些限制和假设适用。
虽然这个代码片段可以解决这个问题,但包含一个解释确实有助于提高文章的质量。请记住,您将来会为读者回答这个问题,而这些人可能不知道您的代码建议的原因。
python中的子类化操作如下:
class WindowElement:
def print(self):
pass
class Button(WindowElement):
def print(self):
pass
下面是一个关于Python的教程,其中也包含类和子类。