Object-oriented python-- - inheritance / polymorphism


## ----- inheritance polymorphism
Inheritance: subclasses fully owns the data parent class
polymorphism: Each subclass has its own method of diversification data can be completely independent of the parent class, you can inherit the parent class on the basis of the increase

Inherited shortcut Ctrl + o

 

1. Data Inheritance

No instances of subclasses init function completely automatically inherit the parent class data

class A:
def __init__(self, name, age):
self.name = name
self.age = age

def sya(self):
print('say...')

B class (A):
Pass
B = B ( 'LILI', 25) to be filled # parameters, or error


Subclass has its own instance of init function
either fully inherit the parent class attributes, increase their attributes on the basis of
class A:
DEF the __init __ (Self, name = None, Age = None):
the self.name name =
self.age = Age

class B(A):
def __init__(self, name, age, sex):
super().__init__(name, age)
self.sex = sex

b = B('LI',25, 'm')
print(b.__dict__)

 

/ Or completely rewritten to use their own property

class A:
def __init__(self, name=None, age=None):
self.name = name
self.age = age


class B(A):
def __init__(self, name, sex):

self.name = name
self.sex = sex

b = B('LI', 'm')
print(b.__dict__)

 

Inherited methods: the subclass automatically inherits the parent class method, you do not need to rewrite the code


May be added to the method of the parent class
class A:
DEF the __init __ (Self, name, Age):
the self.name name =
self.age = Age

def sya(self):
print('say...')


class B(A):

def him (self):
super (). He ()


Completely rewritten
class A:
DEF the __init __ (Self, name, Age):
the self.name name =
self.age = Age

def sya(self):
print('say...')


class B(A):

def him (self):
print ( 'hello')

 


Built-in functions
isinstance (object type)
Returns whether the specified object is an object of some class.
issubclass (type, type)
Returns the specified type is part of a type.

Guess you like

Origin www.cnblogs.com/chenlulu1122/p/11922122.html