• python isinstance和issubclass,区分方法和函数,反射


    一.isinstance和issubclass

    1.isinstance

    class Animal:
        def eat(self):
            print('刚睡醒吃点儿东西')
    
    
    class Cat(Animal):
        def play(self):
            print('猫喜欢玩儿')
    
    c = Cat()
    
    print(isinstance(c, Cat))  # c是一只猫
    print(isinstance(c, Animal))  # 向上判断 c是一只动物

    2.issubclass

     1 class Animal:
     2     def eat(self):
     3         print('刚睡醒吃点儿东西')
     4 
     5 
     6 class Cat(Animal):
     7     def play(self):
     8         print('猫喜欢玩儿')
     9 
    10 c = Cat()
    11 print(issubclass(Cat, Animal))  # 判断Cat类是否是Animal类的子类
    12 print(issubclass(Animal, Cat))  # 判断Animal类是否是Cat类的子类

    二.区分方法和函数

    官方玩法

     1 from types import FunctionType,MethodType  # 方法和函数  FunctionType 函数类型 MethodType 方法类型
     2 from collections import Iterable, Iterator  # 迭代器
     3 
     4 
     5 class Person:
     6     def chi(self):  # 实例方法
     7         print('我要吃鱼')
     8 
     9     @classmethod
    10     def he(cls):
    11         print('我是类方法')
    12 
    13     @staticmethod
    14     def pi():
    15         print('你是真的皮')
    16 
    17 p =Person()
    18 
    19 print(isinstance(Person.chi, FunctionType)) # True
    20 print(isinstance(p.chi, MethodType)) # True
    21 
    22 print(isinstance(p.he, MethodType)) # True
    23 print(isinstance(Person.he, MethodType)) # True
    24 
    25 print(isinstance(p.pi, FunctionType)) # True
    26 print(isinstance(Person.pi, FunctionType)) # True

    野路子

    打印的结果中包含了function. 函数
    method. 方法
     1 def func():
     2     print('我是函数')
     3 
     4 class Foo:
     5     def chi(self):
     6         print('我是吃')
     7 
     8 print(func)  #<function func at 0x0000024817BF1E18>
     9 f = Foo()
    10 f.chi()
    11 print(f.chi)  # <bound method Foo.chi of <__main__.Foo object at 0x0000024817DCC358>>

    三.反射

     1 class Preson:
     2     def __init__(self, name, laopo):
     3         self.name = name
     4         self.laopo = laopo
     5 
     6 
     7 p = Preson('宝宝', '林志玲')
     8 
     9 print(hasattr(p, 'laopo'))  # p这个对象中是否有老婆这个属性
    10 print(getattr(p, 'laopo'))  # p.laopo 获取p这个对象中的老婆属性
    11 
    12 # 设置一个对象属性若存在就修改 不存在就添加到这个对象中
    13 setattr(p, 'laopo', '胡一菲')  # p.laopo = 胡一菲
    14 setattr(p, 'money', 10000000)  # p.money = 10000000
    15 
    16 print(p.laopo)
    17 print(p.money)
    18 
    19 # delattr(p, 'laopo')  # 把对象中的xxx属性移除   != p.laopo = None
    20 print(p.laopo)  #'Preson' object has no attribute 'laopo' 已经移除了对象中的laopo属性所以报错
  • 相关阅读:
    IPv4地址被用光,IPv6将接手
    杀猪盘
    大家都应该看看这个贴子,会让你心明眼亮。 注意到这些变化了吗?中国正在发生的100个变化,越往后读越震惊!
    区块链在中国怎么练?
    区块链到底是什么样的技术呢?
    2019感恩节
    人工智能、大数据、物联网、区块链,四大新科技PK,你更看好谁?
    vue遇见的问题(2)---imported multiple times(转载)
    drf-序列化器的理解
    Django rest_framework序列化many=True参数解释
  • 原文地址:https://www.cnblogs.com/beargod/p/10196691.html
Copyright © 2020-2023  润新知