5.4, obtain object information

Use type

 

 

 

Use isinstance ()

 

 

 

 

 Is one type

 

Is always used when the isinstance () determines the type, the type can be specified and its subclasses "catch."

 Use dir ()

If all properties and methods of an object to be obtained, it may be used dir(), which returns a string containing the list, such as access to all properties and methods of an object str:

 

>>> dir('ABC')
['__add__', '__class__','__len__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

 Similar __xxx__properties and methods in Python are all special purpose, such as __len__the method returns length. In Python, if you call the len()function attempts to get the length of an object, in fact, in len()an internal function, which automatically go to call the object's __len__()method , therefore, it is equivalent to the following code:

 only ( "ABC")

'ABC' only .__ __ ()

 

 Only the properties and methods listed is not enough to meet getattr(), setattr()andhasattr() we can directly manipulate an object's status:

class MyObject(object):
    def __init__(self):
        self.x=9
    def power(self):
        return self.x*self.x
obj=MyObject()
obj.power()

Test the object's properties:

 

 

 

 Method of testing of the object:

 

 When to use getattr(), setattr()andhasattr()

def readImage(fp):
    if hasattr(fp, 'read'): return readData(fp) return None

Suppose we want to read the image from the file stream fp, we must first determine whether the object exists fp read method , if there is, then the object is a stream, if not, you can not read. hasattr()It came in handy.

 

Guess you like

Origin www.cnblogs.com/soberkkk/p/12634534.html