• python 语法 内置函数 hasattr getattr setattr dir


    参考: https://docs.python.org/3/library/functions.html?highlight=hasattr#getattr

    例子1:针对类TestA 做属性操作

    class TestA:
        def fun_1(self):
            print "fun_1"
    
        def fun_2(self):
            print "fun_2"
    
    def fun_2():
        print "fun_3"
    
    test_a = TestA()
    print hasattr(test_a, "fun_1")
    
    fun_a = getattr(test_a,"fun_2")
    print fun_a
    fun_a()
    
    setattr(test_a,"fun_2",fun_2) #对原有函数进行了覆盖。热更新代码常用
    test_a.fun_2()
    print dir(TestA)
    

      结果:

    True
    <bound method TestA.fun_2 of <__main__.TestA instance at 0x0000000002E70E88>>
    fun_2
    fun_3
    ['__doc__', '__module__', 'fun_1', 'fun_2']
    

      

    例子2:针对一个文件内的属性进行条件筛选:

    首先创建新测试文件test_file.py:

    A="a.b"
    class B:
        def fun_1(self):
            pass
    C=[1,2]
    D="png.a"
    E="cc.ee"

    然后对文件进行逻辑处理:

    # coding=utf-8
    
    
    import test_file
    
    # 删选出test_file中所有的str、内有.、不含有png的
    str_list = []
    for item in dir(test_file):  # 查询文件下的属性名
        value = getattr(test_file, item)  # 查询属性名的具体值
        if type(value) != str:
            continue
        if value.find('.') < 0 or value.find('png') >= 0:
            continue
        str_list.append(value)
    
    for item in str_list:
        print item

    结果:

    a.b
    cc.ee
    

    总结:

    setattr(objectnamevalue)

    This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar 123.

    setattr会进行属性覆盖,代码热更可以使用。

    dir([object])

    Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

    If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

    If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

    The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

    • If the object is a module object, the list contains the names of the module’s attributes.
    • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
    • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

    The resulting list is sorted alphabetically. For example:

    >>>
    >>> import struct
    >>> dir()   # show the names in the module namespace  
    ['__builtins__', '__name__', 'struct']
    >>> dir(struct)   # show the names in the struct module 
    ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
     '__initializing__', '__loader__', '__name__', '__package__',
     '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
     'unpack', 'unpack_from']
    >>> class Shape:
    ...     def __dir__(self):
    ...         return ['area', 'perimeter', 'location']
    >>> s = Shape()
    >>> dir(s)
    ['area', 'location', 'perimeter']
    

    Note

     

    Because dir() is supplied primarily(首要的) as a convenience for use at an interactive prompt(敏捷交互?), it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

    dir返回有意义的属性集合,而不是所有属性

    改变自己
  • 相关阅读:
    10、ERP设计之系统基础管理(BS)- 平台化设计
    SendMessage发送自定义消息及消息响应
    【iOS开发】 常遇到的Crash和Bug处理
    UVA 11100 The Trip, 2007 贪心(输出比较奇葩)
    Android_多媒体_SoundPool声音池使用
    Django之逆向解析url
    Oracle中四种循环(GOTO、For、While、Loop)
    Android监控程序本身被卸载方法汇总
    Cocos2dx项目启程一 之 封装属于我的精灵类
    Android-->发送短信页面实现(短信发送以及群发和从电话本中选择联系人)-----------》2
  • 原文地址:https://www.cnblogs.com/sun-shadow/p/9712031.html
Copyright © 2020-2023  润新知