Python Day 8 (3) Gets the object information.

Source: Internet
Author: User
Tags abs

One: Get object information (type and method of object)

Law One:

A basic data type can be judged by the type () function.

>>> type(123)<class ‘int‘>>>> type(‘str‘)<class ‘str‘>>>> type(None)<type(None) ‘NoneType‘>
b If a variable points to a function or class, it can also be type() judged by:
>>> type(abs)<class ‘builtin_function_or_method‘>
c type()函数返回的是对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:
>>> type(123)==type(456)True>>> type(123)==intTrue>>> type(‘abc‘)==type(‘123‘)True>>> type(‘abc‘)==strTrue
D to determine the basic data type can be directly written int , str and so on. If you want to determine whether an object is a function, you can use types the constants defined in the module. (Import Types)
>>>Import types>>>def fn ():  ... pass ... >>> type (FN) ==types. Functiontypetrue>>> type (ABS) ==types. Builtinfunctiontypetrue>>> type ( Lambda x:x) ==types. Lambdatypetrue>>> type ((x for x in range (10)) ==types. Generatortypetrue 

Law II: Using Isinstance () (for class inheritance relationships)
A is not convenient for inheriting relationships with class by using type () . To determine the type of class, you can use the isinstance () function.
B In other words, isinstance () determines whether an object is the type itself, or is on the parent inheritance chain of that type.
C
can usetype()The basic type of judgment can also be usedisinstance()Judge:
        >>> isinstance(‘a‘, str)        True >>> isinstance(123, int) True >>> isinstance(b‘a‘, bytes) True
d isinstance()还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple
  >>> isinstance ([1, 2, 3], (list, tuple))  True >>> Isinstance ((1, 2, 3), (list, tuple))             
E always takes precedence over isinstance () to determine the type, and the specified type and its subclasses can be "clean sweep".

law three: using Dir ()
a If you want to get all the properties and methods of an object, you can use the dir () function, which returns a list that contains a string, for example, to get all the properties and methods of a str object:
 >>> dir (  ' ABC ') [ ' __add__ ',  ' __class__ ',...,  ' __subclasshook__ ', Span class= "string" > ' capitalize ',  ' casefold ',...,  ' Zfill '] 

B
similar to __xxx__ properties and methods are used in Python for special purposes, such as The __len__ method returns the length. In Python, if you call the len () function to try to get the length of an object, in fact, inside the len () function, it automatically calls the __len__ () method of that object, Therefore, the following code is equivalent:
 >>> len (  ' ABC ') 3>>>  ' ABC '. __len__ () 3 

C it is not enough to simply list properties and methods with getattr () , setattr () , and hasattr ( , we can manipulate the state of an object directly
>>> class MyObject(object):... def __init__(self):... self.x = 9... def power(self):... return self.x * self.x...>>> obj = MyObject()

Immediately thereafter, you can test the properties of the object:

>>> hasattr (obj,  ' x ') # have attribute ' x '? true>>> obj.x9 >>> hasattr (obj,  ' y ') # have attribute ' y '? false>>> setattr (obj,  ' y ', 19" # set a property ' Y ' >>> hasattr (obj, # have attribute ' y '? true>>> getattr (obj,  ' y ') # get property ' y ' 19>>> obj.y # get property ' Y ' Span class= "number" >19             

you can pass in a default parameter and, if the property does not exist, return the defaults:
>>> getattr(obj, ‘z‘, 404) # 获取属性‘z‘,如果不存在,返回默认值404404
 
d 也可以获得对象的方法:
>>> hasattr (obj,' power ')# Is there a property of ' power '? True>>> getattr (obj,' power ')# Get property ' Power ' <bound method Myobject.power of <__main__. MyObject Object at0X10077A6A0>>  >>> fn = getattr (obj,   ' power ') /span># get Property ' power ' and assign value to variable fn  < Span style= "font-size:14px" >>>> fn  # fn points to Obj.power<bound method Myobject.power of <__main__. MyObject object at  0X10077A6A0>>  >>> fn ()   # called FN () is the same as calling Obj.power ()  81  


 


Python Day 8 (3) Gets the object information.

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.