Check Python objects

Source: Internet
Author: User

Objects in the programming environment are very similar to objects in the real world. Objects have certain shapes, sizes, weights, and other features. The actual object can also respond to its environment, interact with other objects, or execute tasks. Objects in the computer try to simulate objects in the real world around us, including abstract objects such as documents, calendars, and business processes.

Similar to actual objects, several computer objects may share common features while maintaining their own relatively small variant features. Think about the books you see in the bookstore. Each physical copy of a book may have stains, several broken pages, or a unique identification number. Although each book is a unique object, each book with the same title is only an example of the original template and retains most of the features of the original template.

This is also true for object-oriented classes and class instances. For example, you can see that each Python string is assigned some attributes,Dir ()Functions reveal these attributes. In the previous example, we defined our ownPersonClass, which serves as a template for creating individual person instances. Each instance has its own name and age value and shares its self-introduction capabilities. This is object-oriented.

Therefore, in computer terms, an object is a thing with an identifier and a value. It belongs to a specific type, has specific features, and performs operations in a specific way. In addition, objects inherit many of their attributes from one or more parent classes. Except for keywords and special symbols (like operators, such+,-,*,**,/,%,<,>In python, everything is an object. Python has a rich set of object types: String, integer, floating point, list, tuples, dictionaries, functions, classes, class instances, modules, files, etc.

When you have an arbitrary object (maybe an object passed to the function as a parameter), you may want to know some information about this object. In this section, we will show you how to make Python objects answer the following questions:

    • What is the object name?
    • What type of object is this?
    • What do objects know?
    • What can an object do?
    • Who is the parent object of the object?

Name

Not all objects have names, but all objects with names store their names_ Name __Attribute. Note: The name is derived from the object instead of the variable that references the object. The following example highlights the difference:

Listing 1. What are the names?

 
$ Pythonpython 2.2.2 (#1, Oct 28 2002, 17:22:19) [GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux2type "help", "Copyright ", "Credits" or "License" for more information. >>> dir () # The Dir () function ['_ builtins _', '_ Doc __', '_ name _'] >>> directory = dir # create a new variable >>> directory () # works just like the original object ['_ builtins _', '_ Doc _', '_ name __', 'Directory '] >>> dir. _ name __ # What's your name? 'Dir'> directory. _ name _ # My name is the same 'dir'> _ name _ # And now for something completely different '_ main __'

The module has a name. The Python interpreter is considered as a top-level module or main module. When running python in interactive mode_ Name __Variable value'_ Main __'. Similarly, when the python module is executed from the command line instead of being imported into another module_ Name __Attribute Value'_ Main __'Instead of the actual name of the module. In this way, the module can view its own_ Name __The value is from the row to determine how they are being used.ProgramIs also the main application executed from the command line. Therefore, the following common statement is very common in the python module:

List2. Testing for execution or import

 
If _ name _ = '_ main _': # Do something appropriate here, like calling a # Main () function defined elsewhere in this module. main () else: # Do nothing. this module has been imported by another # module that wants to make use of the functions, # classes and other useful BITs it has defined.

Type

Type ()The function helps us determine whether an object is a string, an integer, or another type of object. It does this by returning a type object. You can set this type objectTypesThe types defined in the module are compared:

 List3. Am I your type?

>>> Import types >>> print types. _ Doc _ DEFINE names for all type symbols known in the standard interpreter. types that are part of optional modules (e.g. array) are not listed. >>> dir (types) ['buffertype', 'builtinfuntype type', 'builtinmethodtype', 'classtype ', 'codetype', 'complextype', 'dictproxytype', 'dicttype ', 'dictionarytype', 'ellipsistype ', 'filetype', 'floattype', 'frametype', 'functiontype', 'generatortype', 'instancetype', 'inttype', 'lambdatype ', 'listtype', 'longtype', 'methodtype', 'letype', 'nontype', 'objecttype', 'slicetype', 'stringtype', 'stringtype', 'tracebacktype ', 'tupletype', 'typetype ', 'unboundmethodtype', 'unicodetype', 'xrangetype ',' _ builtins _ ',' _ Doc __', '_ file _', '_ name _'] >>> S = 'a sample string' >>> type (s) <type 'str' >>> if type (s) is types. stringtype: Print "s is a string "... S is a string >>> type (42) <type 'int' >>>> type ([]) <type 'LIST' >>>> type ({}) <type 'dict '>>> type (DIR) <type 'builtin _ function_or_method'>

Identifier

As we have said earlier, each object has an identifier, type, and value. It is worth noting that multiple variables may reference the same object. Similarly, variables can reference objects that look similar (have the same type and value), but have multiple objects with different identifiers. When you change an object (such as adding one item to the list), this concept of object identity is particularly important, as in the following example,BlistAndClistVariables reference the same list object. As you can see in the example,ID ()The function returns a unique identifier for any given object:

List4. Destination ......

>>> Print ID. _ Doc _ ID (object)-> integerreturn the identity of an object. this is guaranteed to be unique amongsimultaneously existing objects. (Hint: It's the object's memory address.) >>> alist = [1, 2, 3] >>> blist = [1, 2, 3] >>> clist = blist >>> clist [1, 2, 3] >>> blist [1, 2, 3] >>>> alist [1, 2, 3] >>>> ID (alist) 145381412 >>> ID (blist) 140406428 >>>> ID (clist) 140406428 >>> alist is blist # returns 1 if true, 0 if false0 >>>> blist is clist # ditto1 >>> clist. append (4) # add an item to the end of the list >>> clist [1, 2, 3, 4] >>> blist # Same, because they both point to the same object [1, 2, 3, 4] >>> alist # This one only looked the same initially [1, 2, 3]

Attribute

We can see that the object has attributes andDir ()The function returns a list of these attributes. However, sometimes we only want to test whether one or more attributes exist. If an object has an attribute that we are considering, we usually want to retrieve it only. This task can beHasattr ()AndGetattr ()Function, as shown in this example:

Listing 5. Having an attribute; obtaining an attribute

 
>>> Print hasattr. _ Doc _ hasattr (object, name)-> booleanreturn whether the object has an attribute with the given name. (This is done by calling getattr (object, name) and catching exceptions.) >>> print getattr. _ Doc _ getattr (object, name [, default])-> valueget a named attribute from an object; getattr (x, 'y') is equivalent to X. y. when a default argument is given, it is returned when the attribute doesn 'texist; without it, an exception is raised in that case. >>> hasattr (ID, '_ Doc _') 1 >>> print getattr (ID, '_ Doc _') ID (object) -> integerreturn the identity of an object. this is guaranteed to be unique amongsimultaneously existing objects. (Hint: It's the object's memory address .)

Callable

Objects that indicate potential behaviors (functions and methods) can be called. AvailableCallable ()Function Test object callability:

Listing 6. Can you do something for me?

 
>>> Print callable. _ Doc _ callable (object)-> booleanreturn whether the object is callable (I. E ., some kind of function ). note that classes are callable, as are instances with a _ call _ () method. >>> callable ('a string') 0 >>> callable (DIR) 1

Instance

InType ()You can also useIsinstance ()Function Test object to determine whether it is an instance of a specific type or custom class:

Listing 7. Are you one of those instances?

>>> Print isinstance. _ Doc _ isinstance (object, class-or-type-or-tuple)-> booleanreturn whether an object is an instance of a class or of a subclass thereof. with a type as second argument, return whether that is the object's type. the form using a tuple, isinstance (x, (a, B ,...)), is a temporary cut forisinstance (X, A) or isinstance (X, B) or... (etc.). >>> isinstance (42, STR) 0 >>> isinstance ('a string', INT) 0 >>> isinstance (42, INT) 1 >>> isinstance ('a string ', str) 1

Subclass

As we mentioned earlier, instances of custom classes inherit attributes from this class. At the class level, you can define another class based on one class. Similarly, this new class will inherit attributes in a hierarchical manner. Python even supports multi-inheritance. Multi-inheritance means that multiple parent classes can be used to define a class. This new class inherits multiple parent classes.Issubclass ()The function allows us to check whether a class inherits another class:

Listing 8. Are you my mother?

>> print issubclass. _ Doc _ issubclass (C, B)-> booleanreturn whether Class C is a subclass (I. E ., A derived class) of Class B. >>> class superhero (person): # superhero inherits from person ...... def intro (Self): # but with a new superhero intro... "" return an introduction. """... return "Hello, I'm superhero % s and I'm % S. "% (self. name, self. age)...> issubclass (superhero, person) 1 >>> issubclass (person, superhero) 0 >>>
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.