Python object-oriented-Get object information type isinstance getattr setattr hasattr

Source: Internet
Author: User

Python object-oriented-Get object information type isinstance getattr setattr hasattr

I. type () function

You can directly write the basic data type.int,strAnd so on:

>>> Class Animal (object ):
... Pass
...
>>> Type (123)
<Class 'int'>
>>> Type ('20140901 ')
<Class 'str'>
>>> Type (None)
<Class 'nonetype '>
>>> Type (abs)
<Class 'builtin _ function_or_method '>
>>> Type (Animal ())
<Class '_ main _. Animal'>

 

>>> Type (123) = type (456)
True
>>> Type (123) = int
True

Determine whether an object is a function:

>>> Import types
>>> Def fn ():
... Pass
...
>>> Type (fn) = types. FunctionType
True
>>> Type (abs) = types. BuiltinFunctionType
True
>>> Type (lambda x: x) = types. LambdaType
True
>>> Type (x for x in range (10) = types. GeneratorType
True

Ii. isinstance () function

For the class inheritance relationship, usetype()It is inconvenient. To determine the class type, you can useisinstance()Function.

>>> Class Animal (object ):
... Pass
...
>>> Class Dog (Animal ):
... Pass
...
>>> D = Dog ()
>>> Isinstance (d, Dog)
True
>>> Isinstance (d, Animal)
True

Use isinstance () to determine the basic type:

1 >>> isinstance('a', str)2 True3 >>> isinstance(123, int)4 True5 >>> isinstance(b'a', bytes)6 True

You can also determine whether a variable is of certain types. For example, the following code can determine whether a variable is a list or a tuple:

1 >>> isinstance([1, 2, 3], (list, tuple))2 True3 >>> isinstance((1, 2, 3), (list, tuple))4 True

The isinstance () method is used to determine the type. You can overwrite the specified type and its subclass ".

Iii. dir () Functions

To obtain all the attributes and methods of an object, you can usedir()Function, which returns a list containing strings. For example, to obtain all the attributes and methods of a str object:

>>> Dir ('abc ')
['_ Add _', '_ class _', '_ ins INS _', '_ delattr __', '_ dir _', '_ doc _', '_ eq _', '_ format _', '_ ge __', '_ getattribute _', '_ getitem _', '_ getnewargs _', '_ gt _', '_ hash __', '_ init _', '_ iter _', '_ le _', '_ len _', '_ lt __', '_ mod _', '_ mul _', '_ ne _', '_ new _', '_ reduce __', '_ performance_ex _', '_ repr _', '_ rmod _', '_ rmul _', '_ setattr __', '_ sizeof _', '_ str _', '_ subclasshook _', 'capitalize', 'casefold', 'center', 'Count ', 'enabled', 'enabledwith', 'pandtabs ', 'Find', 'format', 'format _ Map', 'index', 'isalnum', 'isalpha ', 'isdecimal ', 'isdigit', 'isidentifier', 'islower', 'isnumeric ', 'isprintable', 'isspace', 'istitle', 'isupload', 'join ', 'ljust ', 'lower', 'lstrip', 'maketrans ', 'partition', 'replace ', 'rfind', 'rindex', 'partition ust ', 'rpartition ', 'rsplit ', 'rdstrip', 'split', 'splits', 'startswith ', 'strip', 'swapcase', 'title', 'translate', 'uppper ', 'zfill']

Similar__xxx__Attributes and methods of are of special purpose in Python, such__len__The return length of the method. In Python, if you calllen()The function tries to get the length of an object. In factlen()Function, which automatically calls__len__()Method, so the following code is equivalent:

1 >>> len('abc')2 33 >>> 'abc'.__len__()4 3

If you want to uselen(myObj)Write__len__()Method:

>>> Class MyDog (object ):
... Def _ len _ (self ):
.... Return 100
...
>>> Dog = MyDog ()
>>> Len (dog)
100

The rest of the List are common attributes or methods, suchlower()Returns a lowercase string:

1 >>> 'abc'.upper()2 'ABC'

IV,getattr(),setattr()Andhasattr()

Test the attributes of this object:

>>> Class MyObject (object ):
... Def _ init _ (self ):
... Self. x = 9
... Def power (self ):
... Return self. x * self. x
...
>>> Obj = MyObject ()
>>> Hasattr (obj, 'x ')
True
>>> Hasattr (obj, 'y ')
False
>>>
>>> Setattr (obj, 'y', 20)
>>> Hasattr (obj, 'y ')
True
>>> Getattr (obj, 'y ')
20
>>> Getattr (obj, 'z ')
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
AttributeError: 'myobject' object has no attribute 'Z'
>>> Getattr (obj, 'z', 100) # specify the default value
100

Method for Testing this object:

>>> Hasattr (obj, 'power ')
True
>>> Getattr (obj, 'power ')
<Bound method MyObject. power of <__ main _. MyObject object at 0x1014be400>
>>> Fn = getattr (obj, 'power ')
>>> Fn
<Bound method MyObject. power of <__ main _. MyObject object at 0x1014be400>
>>> Fn ()
81

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.