前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python isinstance和is

python isinstance和is

作者头像
py3study
发布2020-01-19 15:53:46
2830
发布2020-01-19 15:53:46
举报
文章被收录于专栏:python3python3

一.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属性所以报错
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档