1. isinstance, type, issubclass
isinstance: judge whether the object you give is of type xx
Type: returns the data type of xxx object
issubclass: a subclass to determine whether the xxx class is xxx
class Animal: def eat(self): print("Just woke up to eat something") class Cat(Animal): def play(self): print("Cats like to play") c = Cat() print(isinstance(c, Cat)) # True print(isinstance(c, Animal)) # True a = Animal() print(isinstance(a, Cat)) # Can't judge down False print(type(a)) # Return a Data type of print(type(c)) # Precisely tell you the data type of this object # judge.xx Is class A xxxx Subclasses of classes print(issubclass(Cat, Animal)) # True print(issubclass(Animal, Cat)) # False
2. How to distinguish methods and functions
In class:
Instance method
If it is a class name. Method function
If it is an object, method
Class method: all methods
Static methods: all functions
from types import MethodType, FunctionType
isinstance()
from types import FunctionType, MethodType # Modules introducing methods and functions class Person: def chi(self): # Example method print("I want to eat fish.") @classmethod def he(cls): print("I'm a class method") @staticmethod def pi(): print("You are the real skin") p = Person() print(isinstance(Person.chi, FunctionType)) # True print(isinstance(p.chi, MethodType)) # True print(isinstance(p.he, MethodType)) # True print(isinstance(Person.he, MethodType)) # True print(isinstance(p.pi, FunctionType)) # True print(isinstance(Person.pi, FunctionType)) # True
3. reflection
There are four functions
attr: attribute
getattr()
Get xxx property value from xxx object
hasattr()
Determine whether xxx property value exists in xxx object
delattr()
Remove xxx property from xxx object
setattr()
Set xxx property in xxx object to xxxx value
class Person: def __init__(self, name,wife): self.name = name self.wife = wife p = Person("baby", "Lin Chiling") print(hasattr(p, "wife")) print(getattr(p, "wife")) # p.wife setattr(p, "wife", "Hu Yi Fei") # p.wife = Hu Yi Fei setattr(p, "money", 100000) # p.money = 100000 print(p.wife) print(p.money) delattr(p, "wife") # Put the xxx Attribute Removal. Not at all p.wife = None print(p.wife)