Python:如何从超类生成子类?
在Python中,如何从超类生成子类Python:如何从超类生成子类?,python,class,Python,Class,在Python中,如何从超类生成子类 class Subclass (SuperClass): # Subclass stuff here Class2是Class1的一个子类,您可以使用: class DerivedClassName(BaseClassName): 有关详细信息,请参阅。类MySubClass(MySuperClass): 定义初始化(自): MySuperClass.\uuuuu初始化\uuuuuuu(自) # python文档中的详细说明如下在pyth
class Subclass (SuperClass):
# Subclass stuff here
Class2是Class1的一个子类,您可以使用:
class DerivedClassName(BaseClassName):
有关详细信息,请参阅。类MySubClass(MySuperClass):
定义初始化(自):
MySuperClass.\uuuuu初始化\uuuuuuu(自)
#
python文档中的详细说明如下在python中进行子类化:
class Mammal(object):
#mammal stuff
class Dog(Mammal):
#doggie stuff
class WindowElement:
def print(self):
pass
class Button(WindowElement):
def print(self):
pass
下面是一个关于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()
或者,更好的是,使用Python的内置函数super()
(请参阅/文档)可能是调用父级进行初始化的更好方法:
# 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__()
还有另一种方法可以使用函数
type()
,在python中动态生成子类:
在处理元类时,通常需要使用此方法。当您想要执行一些较低级别的自动化时,这会改变python创建类的方式。很可能你永远不需要这样做,但当你这样做的时候,你就会知道你在做什么。class BankAccount:
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())
定义初始值(自身,平衡=0):
self.balance=int(balance)
def支票余额(自身):##检查期初余额。。。。
回归自我平衡
def存款(自身,存款金额=1000):##接受现金存款金额并相应更新余额。
self.deposit\u amount=存款金额
自身余额+=存款金额
回归自我平衡
def draw(self,draw_amount=500):##接收现金提款金额并相应更新余额
如果self.balance
在上面的答案中,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
是符合的仅关键字参数)。如果要添加更多代码,只需定义\uuuu init\uuuu
方法,否则仍将使用原始init方法(尽管值得一提,并且是完全有效的代码)我认为这个问题很模糊,可能会添加更多的代码。最好提供太多的信息,而不是不够,在OP实施时,最后会提出另一个问题。:)请注意,Python改变了您进行子类化的方式,因此有两种方法,它们不会混合使用。如果你混音,你会得到一个错误。阅读这篇文章可以看出其中的区别:OTOH,有些人警告不要使用super
,特别是对于新的Python程序员(例如Lutz)。我避免使用它。避免使用super
的唯一原因是,如果您不了解super
在Python中的工作方式与super
/在其他语言中的工作方式之间的差异。诚然,这对来自其他语言的人来说并不明显,但我不会得出结论,认为这是“值得警惕”的东西。它确实有效。它只是工作方式不同。在你抱怨得到了出乎意料的结果之前,先阅读一下它在Python中的实际功能。如果你对它的功能做了解释,这个答案会更有帮助。尽管这段代码可能有助于解决问题,但它没有解释为什么和/或它如何回答这个问题。提供这种额外的环境将大大提高其长期教育价值。请在回答中添加解释,包括适用的限制和假设。虽然此代码片段可以解决问题,但确实有助于提高文章质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。酷。这就是我实际寻找的,也就是说,一个没有扩展/覆盖到super的子类。
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__()
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())
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
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__])