类的补充__反射

一.反射。

二.isinstance()函数

三.type()函数。

四.issubclass()函数。

一.反射

 反射一共就四个函数:

getattr(object,name)
从xxx对象中获取到xxx属性值
hasattr(object,name)
判断xxx对象中是否有xxx属性值
delattr(object,name)
从xxx对象中删除xxx属性
setattr(object,name)
设置xxx对象中的xxx属性为xxxx值

attr的全称是 attribute 属性的意思
# 对于模块而言可以使用getattr, hasattr, 同样对于我们的对象也可以执行类似的操作

class Person:
    def __init__(self, name, laopo):
        self.name = name
        self.laopo = laopo

p = Person("宝宝", "林志玲")

print(hasattr(p, "laopo")) #
print(getattr(p, "laopo")) # p.laopo

setattr(p, "laopo", "胡一菲") # p.laopo = 胡一菲
setattr(p, "money", 100000000000) # p.money = 100000000

print(p.laopo)
print(p.money)

delattr(p, "laopo") # 把对象中的xxx属性移除.  != p.laopo = None
print(p.laopo)

二.isinstance()函数.

isinstance: 判断你给对象是否是xx类型的. (向上判断)

三.type()函数.

四.issubclass()函数.

 

五.其他零星补充:

如何判断是方法还是函数:

from types import FunctionType, MethodType # 方法和函数
from collections import Iterable, Iterator # 迭代器


class Person:
    def chi(self): # 实例方法
        print("我要吃鱼")

    @classmethod
    def he(cls):
        print("我是类方法")

    @staticmethod
    def pi():
        print("泥溪镇地皮")


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
实例方法:
  1. 如果使用   对象.实例方法   方法
  2. 如果使用     类.实例方法     函数
  3.  静态方法都是函数

猜你喜欢

转载自www.cnblogs.com/lgw1171435560/p/10152197.html