Python:我如何从一个超类创build一个子类?

在Python中,你如何从一个超类创build一个子类?

使用“super”(请参阅Python Built-in ,super)可能是调用父级进行初始化的稍好方法:

# Initialize using Parent # class MySubClass(MySuperClass): def __init__(self): MySuperClass.__init__(self) # Better initialize using Parent (less redundant). # class MySubClassBetter(MySuperClass): def __init__(self): super(MySubClassBetter, self).__init__() 

一个英雄的小例子:

 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) # <the rest of your custom initialization code goes here> 

python文档中有关inheritance的部分更详细地解释了它

 class Class1(object): pass class Class2(Class1): pass 

Class2是Class1的一个子类

你用:

 class DerivedClassName(BaseClassName): 

有关详细信息,请参阅Python文档,第9.5节 。

还有一种方法可以用函数type()dynamic地在python中创build子类:

 SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__() 

在处理元类时通常要使用这个方法。 当你想做一些较低层次的自动化时,改变python创build类的方式。 很可能你永远不会需要这样做,但是当你这样做,比你已经知道你在做什么。

 class Subclass (SuperClass): # Subclass stuff here 
 class Mammal(object): #mammal stuff class Dog(Mammal): #doggie stuff 

Python中的子类化过程如下:

 class WindowElement: def print(self): pass class Button(WindowElement): def print(self): pass 

这里是一个关于Python的教程 ,也包含类和子类。

 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())