mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-24 10:01:38 +00:00
[python3/en] Add single inheritance section
This commit is contained in:
parent
4d3637bfc4
commit
9b6d84309c
@ -740,7 +740,101 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
|
|
||||||
####################################################
|
####################################################
|
||||||
## 6.1 Multiple Inheritance
|
## 6.1 Inheritance
|
||||||
|
####################################################
|
||||||
|
|
||||||
|
# Inheritance allows new child classes to be defined that inherit methods and
|
||||||
|
# variables from their parent class.
|
||||||
|
|
||||||
|
# Using the Human class defined above as the base or parent class, we can
|
||||||
|
# define a child class, Superhero, which inherits the class variables like
|
||||||
|
# "species", "name", and "age", as well as methods, like "sing" and "grunt"
|
||||||
|
# from the Human class, but can also have its own unique properties.
|
||||||
|
|
||||||
|
# To take advantage of modularization by file you could place the classes above in their own files,
|
||||||
|
# say, human.py
|
||||||
|
|
||||||
|
# To import functions from other files use the following format
|
||||||
|
# from "filename-without-extension" import "function-or-class"
|
||||||
|
|
||||||
|
from human import Human
|
||||||
|
|
||||||
|
|
||||||
|
# Specify the parent class(es) as parameters to the class definition
|
||||||
|
class Superhero(Human):
|
||||||
|
|
||||||
|
# If the child class should inherit all of the parent's definitions without
|
||||||
|
# any modifications, you can just use the "pass" keyword (and nothing else)
|
||||||
|
# but in this case it is commented out to allow for a unique child class:
|
||||||
|
# pass
|
||||||
|
|
||||||
|
# Child classes can override their parents' attributes
|
||||||
|
species = 'Superhuman'
|
||||||
|
|
||||||
|
# Children automatically inherit their parent class's constructor including
|
||||||
|
# its arguments, but can also define additional arguments or definitions
|
||||||
|
# and override its methods such as the class constructor.
|
||||||
|
# This constructor inherits the "name" argument from the "Human" class and
|
||||||
|
# adds the "superpower" and "movie" arguments:
|
||||||
|
def __init__(self, name, movie=False,
|
||||||
|
superpowers=["super strength", "bulletproofing"]):
|
||||||
|
|
||||||
|
# add additional class attributes:
|
||||||
|
self.fictional = True
|
||||||
|
self.movie = movie
|
||||||
|
self.superpowers = superpowers
|
||||||
|
|
||||||
|
# The "super" function lets you access the parent class's methods
|
||||||
|
# that are overwritten by the child, in this case, the __init__ method.
|
||||||
|
# This calls the parent class constructor:
|
||||||
|
super().__init__(name)
|
||||||
|
|
||||||
|
# overload the sing method
|
||||||
|
def sing(self):
|
||||||
|
return 'Dun, dun, DUN!'
|
||||||
|
|
||||||
|
# add an additional class method
|
||||||
|
def boast(self):
|
||||||
|
for power in self.superpowers:
|
||||||
|
print("I wield the power of {pow}!".format(pow=power))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
sup = Superhero(name="Tick")
|
||||||
|
|
||||||
|
# Instance type checks
|
||||||
|
if isinstance(sup, Human):
|
||||||
|
print('I am human')
|
||||||
|
if type(sup) is Superhero:
|
||||||
|
print('I am a superhero')
|
||||||
|
|
||||||
|
# Get the Method Resolution search Order used by both getattr() and super()
|
||||||
|
# This attribute is dynamic and can be updated
|
||||||
|
print(Superhero.__mro__) # => (<class '__main__.Superhero'>,
|
||||||
|
# => <class 'human.Human'>, <class 'object'>)
|
||||||
|
|
||||||
|
# Calls parent method but uses its own class attribute
|
||||||
|
print(sup.get_species()) # => Superhero
|
||||||
|
|
||||||
|
# Calls overloaded method
|
||||||
|
print(sup.sing()) # => Dun, dun, DUN!
|
||||||
|
|
||||||
|
# Calls method from Human
|
||||||
|
sup.say('Spoon') # => Tick: Spoon
|
||||||
|
|
||||||
|
# Call method that exists only in Superhero
|
||||||
|
sup.boast() # => I wield the power of super strength!
|
||||||
|
# => I wield the power of bulletproofing!
|
||||||
|
|
||||||
|
# Inherited class attribute
|
||||||
|
sup.age = 31
|
||||||
|
print(sup.age) # => 31
|
||||||
|
|
||||||
|
# Attribute that only exists within Superhero
|
||||||
|
print('Am I Oscar eligible? ' + str(sup.movie))
|
||||||
|
|
||||||
|
####################################################
|
||||||
|
## 6.2 Multiple Inheritance
|
||||||
####################################################
|
####################################################
|
||||||
|
|
||||||
# Another class definition
|
# Another class definition
|
||||||
@ -766,20 +860,16 @@ if __name__ == '__main__':
|
|||||||
print(b.fly)
|
print(b.fly)
|
||||||
|
|
||||||
# To take advantage of modularization by file you could place the classes above in their own files,
|
# To take advantage of modularization by file you could place the classes above in their own files,
|
||||||
# say, human.py and bat.py
|
# say, superhero.py and bat.py
|
||||||
|
|
||||||
# To import functions from other files use the following format
|
# To import functions from other files use the following format
|
||||||
# from "filename-without-extension" import "function-or-class"
|
# from "filename-without-extension" import "function-or-class"
|
||||||
|
|
||||||
# superhero.py
|
# superhero.py
|
||||||
from human import Human
|
from superhero import Superhero
|
||||||
from bat import Bat
|
from bat import Bat
|
||||||
|
|
||||||
# Batman inherits from both Human and Bat
|
# Batman inherits from both Superhero and Bat
|
||||||
class Batman(Human, Bat):
|
class Batman(Superhero, Bat):
|
||||||
|
|
||||||
# Batman has its own value for the species class attribute
|
|
||||||
species = 'Superhero'
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
# Typically to inherit attributes you have to call super:
|
# Typically to inherit attributes you have to call super:
|
||||||
@ -789,7 +879,8 @@ class Batman(Human, Bat):
|
|||||||
# So instead we explicitly call __init__ for all ancestors.
|
# So instead we explicitly call __init__ for all ancestors.
|
||||||
# The use of *args and **kwargs allows for a clean way to pass arguments,
|
# The use of *args and **kwargs allows for a clean way to pass arguments,
|
||||||
# with each parent "peeling a layer of the onion".
|
# with each parent "peeling a layer of the onion".
|
||||||
Human.__init__(self, 'anonymous', *args, **kwargs)
|
Superhero.__init__(self, 'anonymous', movie=True,
|
||||||
|
superpowers=['Wealthy'], *args, **kwargs)
|
||||||
Bat.__init__(self, *args, can_fly=False, **kwargs)
|
Bat.__init__(self, *args, can_fly=False, **kwargs)
|
||||||
# override the value for the name attribute
|
# override the value for the name attribute
|
||||||
self.name = 'Sad Affleck'
|
self.name = 'Sad Affleck'
|
||||||
@ -802,8 +893,8 @@ if __name__ == '__main__':
|
|||||||
sup = Batman()
|
sup = Batman()
|
||||||
|
|
||||||
# Instance type checks
|
# Instance type checks
|
||||||
if isinstance(sup, Human):
|
if isinstance(sup, Superhero):
|
||||||
print('I am human')
|
print('I am a superhero)
|
||||||
if isinstance(sup, Bat):
|
if isinstance(sup, Bat):
|
||||||
print('I am bat')
|
print('I am bat')
|
||||||
if type(sup) is Batman:
|
if type(sup) is Batman:
|
||||||
@ -811,10 +902,13 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
# Get the Method Resolution search Order used by both getattr() and super().
|
# Get the Method Resolution search Order used by both getattr() and super().
|
||||||
# This attribute is dynamic and can be updated
|
# This attribute is dynamic and can be updated
|
||||||
print(Batman.__mro__) # => (<class '__main__.Batman'>, <class 'human.Human'>, <class 'bat.Bat'>, <class 'object'>)
|
print(Batman.__mro__) # => (<class '__main__.Batman'>,
|
||||||
|
# => <class 'superhero.Superhero'>,
|
||||||
|
# => <class 'human.Human'>,
|
||||||
|
# => <class 'bat.Bat'>, <class 'object'>)
|
||||||
|
|
||||||
# Calls parent method but uses its own class attribute
|
# Calls parent method but uses its own class attribute
|
||||||
print(sup.get_species()) # => Superhero
|
print(sup.get_species()) # => Superhuman
|
||||||
|
|
||||||
# Calls overloaded method
|
# Calls overloaded method
|
||||||
print(sup.sing()) # => nan nan nan nan nan batman!
|
print(sup.sing()) # => nan nan nan nan nan batman!
|
||||||
@ -827,10 +921,10 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
# Inherited class attribute
|
# Inherited class attribute
|
||||||
sup.age = 100
|
sup.age = 100
|
||||||
print(sup.age)
|
print(sup.age) # => 100
|
||||||
|
|
||||||
# Inherited attribute from 2nd ancestor whose default value was overridden.
|
# Inherited attribute from 2nd ancestor whose default value was overridden.
|
||||||
print('Can I fly? ' + str(sup.fly))
|
print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user