1. Basic
class Student(object): name = 'Student' # default value def __init__(self, name, score): self.score = score # public self.__name = name # private def set_name(name): self.__name = name def get_name(): return self.__name
2. Inheritance
class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') def run_twice(animal): animal.run() animal.run()
Run the example:
>>> run_twice(Animal()) Animal is running... Animal is running... When we pass in an instance of Dog, run_twice() prints out: >>> run_twice(Dog()) Dog is running... Dog is running... When we pass in an instance of Cat, run_twice() prints: >>> run_twice(Cat()) Cat is running... Cat is running...
The advantage of polymorphism is that whoever passes the parameter will call whose method. have an inheritance relationship with each other.
object is the inherited parent class of all classes.
3. Determine the inheritance relationship
dog = Dog() print(isinstance(dog, Animal)) # Animal
True
4. Dynamic binding function
class Student(object): pass def set_age(self, age): # define a function as an instance method self.age = age Student.set_score = set_score # Add function to Class s = Student() s.set_score(100) # can be called
Only add methods to an instance
from types import MethodType class Student(object): pass def set_age(self, age): # define a function as an instance method self.age = age s = Student() s.set_score= MethodType(set_score, s) # Bind a method to the instance s.set_score(100) # can be called s2 = Student() s2.set_score(100) # cannot be called
5.