当前位置: 移动技术网 > IT编程>脚本编程>Python > python面向对象(反射)(四)

python面向对象(反射)(四)

2018年12月21日  | 移动技术网IT编程  | 我要评论

搜搜街,官场特工,261041

1. isinstance, type, issubclass

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

    type: 返回xxx对象的数据类型

    issubclass: 判断xxx类是否xxx的子类

class animal:
    def eat(self):
        print("刚睡醒吃点儿东西")

class cat(animal):
    def play(self):
        print("猫喜欢玩儿")

c = cat()

print(isinstance(c, cat)) # true
print(isinstance(c, animal)) # true

a = animal()
print(isinstance(a, cat)) # 不能向下判断  false

print(type(a)) # 返回 a的数据类型
print(type(c)) # 精准的告诉你这个对象的数据类型

# 判断.xx类是否是xxxx类的子类
print(issubclass(cat, animal))  # true
print(issubclass(animal, cat))  # false

 

2. 如何区分方法和函数

    在类中:

        实例方法

            如果是类名.方法  函数

            如果是对象.方法  方法

        类方法: 都是方法

        静态方法: 都是函数

    from types import methodtype, functiontype

    isinstance()

from types import functiontype, methodtype  #  引入方法和函数的模块
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

 

3. 反射

    一共就4个函数

    attr: attribute

    getattr()

        从xxx对象中获取到xxx属性值

    hasattr()

        判断xxx对象中是否有xxx属性值

    delattr()

        从xxx对象中删除xxx属性

    setattr()

        设置xxx对象中的xxx属性为xxxx值

 

class person:
    def __init__(self, name,wife):
        self.name = name
        self.wife = wife


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

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

setattr(p, "wife", "胡一菲") # p.wife = 胡一菲
setattr(p, "money", 100000) # p.money = 100000

print(p.wife)
print(p.money)

delattr(p, "wife") # 把对象中的xxx属性移除. 并不是p.wife = none
print(p.wife)

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网