Use hasattr (), getattr (), setattr () function

1. hasattr(object, name)

  The name attribute is determined whether there is a target object, of course, for the python objects, properties and methods comprising a variable; the returns True, False if no; Note that the parameter is a string type name, it is determined whether the variable is to The method, which names as strings mass participation; getattr and also setattr;

Copy the code
Copy the code
>>> 
>>> class A():
    name = 'python'
    def func(self):
        return 'A()类的方法func()'

    
>>> 
>>> hasattr(A, 'name')
True
>>> 
>>> hasattr(A, 'age')
False
>>> 
>>> hasattr(A, 'func')
True
>>> 
Copy the code
Copy the code

  2. getattr(object, name[, default])

  Value acquisition target object attribute, the attribute value is returned if present, is not present if the two cases, one is no default parameter directly error; given default parameters, if the object does not have a name attribute, then returns given default value; if the given property name is the method of the object, the return is a function of the object, call the function object to obtain the function return value; call word is after the function objects parentheses, such as func is to the func ();

  Also note that if the method given FUNC () is an example of a function, then the write getattr (A, 'func') (), as fun () is an example of a function, it can not be called with A class object, should be written getattr (a (), 'func') (); class distinction instance function and a function of what can be simply understood, the function definition instance, direct def func (self) :, then the definition is the only class instantiated, using the instantiation object class to invoke; while class function definition, @classmethod need to decorate, default parameter function generally CLS, class function may be called directly by the class object, without the need for classes examples of;

Copy the code
Copy the code
>>> 
>>> class A():
    name = 'python'
    def func(self):
        return 'Hello world'

    
>>> 
>>> getattr(A, 'name')
'python'
>>> 
>>> getattr(A, 'age')    # age变量不存在则报错

Traceback (most recent call last):
  File "<pyshell#464>", line 1, in <module>
    getattr(A, 'age')
AttributeError: class A has no attribute 'age'
>>> 
>>> getattr(A, 'age', 20)
20
>>> 
>>> getattr(A, 'func')
<unbound method A.func>
>>>
    getattr (A, 'FUNC') ()
Traceback (MOST Recent Last Call):
function can not be called an object class A, the error>>> getattr (A, 'func'

  File "<470 pyshell #>", Line. 1, in <Module1 >
TypeError: unbound method func() must be called with A instance as first argument (got nothing instead)
>>> 
>>> getattr(A(), 'func')()
'Hello world'
>>> 

>>> class A(object):
    name = 'python'
    @classmethod
    def func(cls):
      return 'the method of A object.'

>>> 
>>> getattr(A, 'func')()
'the method of A object.'
>>>

Copy the code
Copy the code

  3. setattr(object, name, value)

  Assigned to the name attribute value object object, if the object was originally given attribute name exists, it will change setattr property is given value; if the object had attribute name does not exist, setattr property created in the object, and assign for a given value;

Copy the code
Copy the code
>>> 
>>> class A():
    name = 'python'
    def func(self):
        return 'Hello world'

    
>>> 
>>> setattr(A, 'name', 'java')
>>> getattr(A, 'name')
'java'
>>> 
>>> setattr(A, 'age', 20)
>>> getattr(A, 'age')
20
>>> 
Copy the code
Copy the code

 

 

  First determines whether there is a general property of objects, if present, is returned; if not, then add attributes to the object and assignment; if-else simple determination:

Copy the code
>>> 
>>> class A():
    name = 'python'
    def func(self):
        return 'Hello world'

    
>>> 
>>> if hasattr(A, 'age'):
    print getattr(A, 'age')
else:
    setattr(A, 'age', 20)

    
>>> 
>>> getattr(A, 'age')
20
>>> 

高级使用
# - * - Coding: UTF-. 8 - * - Import SYS
 Import Platform class InfoCollection ( Object ): DEF the collect ( Self ): # collecting platform information # first determines the current platform, depending on the platform to perform different methods the try : FUNC = getattr ( Self , Platform . System () . Lower ()) info_data = FUNC () formatted_data = Self . build_report_data ( info_data ) return




formatted_data except AttributeError: sys.exit("不支持当前操作系统: [%s]! " % platform.system()) @staticmethod def linux(): from plugins.collect_linux_info import collect return collect() @staticmethod def windows(): from plugins.collect_windows_info import Win32Info return Win32Info().collect() @staticmethod DEF build_report_data ( Data ): # a left interface to facilitate data after filtering functions or increases Pass return Data

Guess you like

Origin www.cnblogs.com/zyqui/p/12456638.html