码迷,mamicode.com
首页 > 其他好文 > 详细

内置函数

时间:2018-06-30 22:56:04      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:delattr   操作   通过   elf   自动   pass   内容   应该   ==   

1. isinstance()

  • isinstance(对象A,类B),用来判断对象A是不是类B的实例
  • 可以专门用isinstance()来判断数据类型
class Foo:
    pass

obj=Foo()
print(isinstance(obj,Foo))
============================
True
  • 用来判断是否属于数据类型
d={‘a‘:1,‘b‘:2}

print(isinstance(d,dict))
===========================
True

2. issubclass()

  • 判断一个类是否为另一个类的子类
class Parent:
    pass

class Sub(Parent):
    pass

print(issubclass(Sub,Parent))
================================
True

二、反射

1. 什么是反射

  • 通过字符串来操作类或者对象的属性

2. hasattr

  • 用来判断属性是否存在
  • 语法:hasattr(对象名或类名,‘字符串形式的属性名‘)
  • 底层原理是查看__dict__中有没有
class People:
    country=‘China‘
    def __init__(self,name,age):
        self.name=name
        self.age=age

obj=People(‘xut‘,18)
print(hasattr(obj,‘name‘))
print(hasattr(People,‘name‘)) # 这是对象的属性
print(hasattr(People,‘country‘))

========================================================
True
False
True

3. getattr

  • 查看属性的内容
  • 语法:getattr(类名或对象名,‘字符串形式的属性名‘,,‘如果属性找不到可以在这里添加注释,通常写为None‘)
class People:
    country=‘China‘
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def eat(self):
        print(‘eat......‘)

obj=People(‘xut‘,18)
print(getattr(People,‘eat‘))
print(People.eat)
print(getattr(obj,‘eat‘))
print(obj.eat)
# 找不到可以加注释,否则报错
print(getattr(obj,‘e‘,‘aaaaaa‘))
=============================================================
<function People.eat at 0x0000022EB81BD1E0>
<function People.eat at 0x0000022EB81BD1E0>
<bound method People.eat of <__main__.People object at 0x0000022EB81DF400>>
<bound method People.eat of <__main__.People object at 0x0000022EB81DF400>>

aaaaaa

4. setattr

  • 修改属性的内容
  • 语法:setattr(对象或类名,‘字符串属性名‘,修改的内容)
class People:
    country=‘China‘
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def eat(self):
        print(‘eat......‘)

obj=People(‘xut‘,18)
setattr(obj,‘age‘,20)
print(obj.age)
========================================
20

5. delattr

  • 删除属性的内容
  • 语法:delattr(对象或类名,‘字符串形式的属性名‘)
class People:
    country=‘China‘
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def eat(self):
        print(‘eat......‘)

obj=People(‘xut‘,18)
print(obj.__dict__)
delattr(obj,‘name‘)
print(obj.__dict__)
=======================================
{‘name‘: ‘xut‘, ‘age‘: 18}
{‘age‘: 18}

6. 应用案例:

class Ftp:
    def __init__(self,ip,port):
        self.ip=ip
        self.port=port

    def get(self):
        print(‘Get Function‘)

    def put(self):
        print(‘Put Function‘)

    def run(self):
        while True:
            choice=input(‘>>>:‘).strip()
            method=getattr(self,choice,None)
            if method is None:
                print(‘输入的名字不存在‘)
            else:
                method()
obj=Ftp(‘10.0.0.1‘,23)
obj.run()
====================================================
>>>:get
Get Function
>>>:put
Put Function
>>>:

三、内置方法

  • __开头__结尾的,会满足某种条件自动触发

1. str

  • __str__会在在打印对象时,自动触发,并且__str__下的return必须返回字符串类型
# 自定义的类,默认打印对象时,只打印对象的内存地址
class Foo:
    pass

obj=Foo()
print(obj)
==============================================
<__main__.Foo object at 0x000002819764A5F8>

# 而内置的数据类型,可以打印出对象的信息
d={‘a‘:1,‘b‘:2}
print(d)
==============================================
{‘a‘: 1, ‘b‘: 2}
  • 定制打印对象的格式
class People:
    def __init__(self,name,age):
        self.name=name
        self.age=age
# 在对象被打印时,自动触发,应该在该方法内采集与对象self有关的信息,然后拼成字符串返回
    def __str__(self):
        return ‘name:%s  age:%s‘ %(self.name,self.age)

obj=People(‘xut‘,18)
print(obj)
print(obj)
===========================================================
name:xut  age:18
name:xut  age:18

2. del

  • __del__会在对象被删除前,自动触发,__del__也叫析构方法

① 程序结束会触发__del__

class People:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __del__(self):
        print(‘run------------->‘)

obj=People(‘xut‘,18)
print(‘程序运行结束,程序内存空间被回收,触发__del__‘)
====================================================
程序运行结束,程序内存空间被回收,触发__del__
run------------->

说明:程序运行完了,内存空间就会被回收清除(Python解释器的回收),即被删除,就会触发__del__

② 主动删除对象,会触发__del__

class People:
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __del__(self):
        print(‘run------------->‘)

obj=People(‘xut‘,18)
del obj
print(‘程序运行结束‘)
======================================
run------------->
程序运行结束

③ 同时占用系统资源和应用程序资源时,需要__del__配合删除

class People:
    def __init__(self,name,age):
        self.name=name
        self.age=age
        # open打开文件会同时占用系统和应用程序的资源
        self.f=open(‘a.txt‘,‘rt‘,encoding=‘utf-8‘)

    def __del__(self):
        # 只是在应用程序中删除,还需要回收系统资源
        self.f.close()

obj=People(‘xut‘,18)

print(‘程序运行结束‘)

内置函数

标签:delattr   操作   通过   elf   自动   pass   内容   应该   ==   

原文地址:https://www.cnblogs.com/itone/p/9248900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!