Python Learning: Python Object-oriented (2)

Source: Internet
Author: User

Transfer from http://www.cnblogs.com/BeginMan/p/3191037.html

First, class

A class is a data structure that encapsulates data and operations.

The declaration of a class is very similar to the declaration of a function:

Class Newclass (object): "" "Class    documentation string" ""## body    

Note: A class is an object (in Python, everything is an object), but when a class is defined, it is not an implementation of an object.

Second, class properties

In
object-oriented programming and thinking, the concept of class attributes appears. In Java, instance variables and static variables of a class are called generic variables (class ' s variables, often referred to as class variables) or data fields (Java language Programming (Basic), mechanical industry Press, p185). In the object-oriented programming language Python, a class property is a variable defined in a class. In C + +, a class property is a data item that describes the common characteristics of all the objects of a class, and its property values are the same for any object instance. Different programming languages have different definitions. Some languages do not distinguish between static types, so it is not possible to use static to indicate whether this property is a class property. Only static modified properties allow data sharing between objects.
Property: is a data or function element that belongs to another object.

An interesting phenomenon in Python is that when a property is accessed, it is also an object. Having its own properties can be accessed, which creates a property chain.

1. Data properties of the class:

Is the variable that defines the class, the static variable, or the static data. They are bound to the owning class object and do not depend on any class instances. This type of data is equivalent to adding static before the variable.

Class Newclass (object):    foo =    print newclass.foo      #100newclass.foo+=100#       $

Class properties are not the same as instance properties.

2. Methods

Method is also a class property.

3. View class Properties

Use the built-in function dir () or the dictionary property of the class __dict__ can.

class Newclass (object):  Def foo (self): passprint< Span style= "COLOR: #000000" > dir (newclass) #[' __class__ ' , ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __module__ ', ' __new__ ', ' __reduce_ _ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __str__ ', ' __weakref__ ', ' foo '] print Newclass. __dict__ #{' __dict__ ': <attribute ' __dict__ ' of ' newclass ' objects>, ' __module__ ': ' __main__ ', ' foo ': <function foo at 0x00b00a30> __weakref__ ': <attribute ' __weakref__ ' of ' newclass ' objects>, ' __doc__ ': None}     

ClassNewclass (object):"""Python Class"""DefFoo (self):PassPrint Newclass.__name__#newclassprint newclass. __doc__ #python class Print Newclass. __bases__ # (<type ') Object ', ' print newclass. __base__ #<type ' object ' > print newclass. __module__ #__main__< Span style= "COLOR: #0000ff" >print newclass. __class__ #<type "type                 

Third, examples

1. Examples of classes

A class is a data structure definition type, then an instance is a variable that declares this type.

ClassNewclass (object):python classdef foo (self): passc = Newclass () print type (c) #<class ' __main__.newclass", whereas before the Python2.2 version, the instance is "instance type" Never consider the class from which the print type (0) # <type ' int ' >print type (newclass) #<type ' type ' >print type (int) #< Span style= "COLOR: #008000" ><type ' type ' > both are type         

Note that after the 2.2 release, when you define a modern class, you have created a new type.

2, __init__ () "constructor" method

Without creating an instance from new, you don't define a constructor, and Python creates an object for you

__init__ () is the first method that is called after the interpreter creates an instance for you

If no special Method __init__ () is defined (or overwritten). No special action is applied to the instance.

3, __new__ () "constructor" method

Compared to __init__ (), __new__ () is more like a real constructor.

4, __del__ () "Deconstruction" method

Iv. class attributes and instance properties

Reference: http://www.pythonfan.org/thread-9827-1-1.html

Class properties in Python simply store data related to the class, regardless of the instance of the class. Class properties are similar to static member variables in Java. Class properties for accessing Python can use the class name + "." + Property name, if an instance of the class does not have a variable with the same name, it can be accessed using an instance. If the instance contains a property with the same name as the Class property, the attribute is accessed in the instance when the property is accessed with that instance.

ClassTest (): myversion="1.0" # declares a class property and assigns a value of 1.0 t=test () # to generate an instance test.myversion # Use class space to access class properties, output as 1.0t.myversion # Using instance space to access class properties, output to 1.0test.myversion="2.0" #  Use class space to update class properties Test.myversion # Use class space to access class properties, output to 2.0t.myversion # Use instance space to access class properties, output as 2.0  

You can set and update class properties only when you use class space to reference class properties. If an attempt is made to use an instance space to refer to a class property for updating, the instance (if there is no property with the same name) creates an instance property with the same name as the Class property. The instance property blocks the instance's access to the class property until the instance's property with the same name is cleared out.

t.myversion='3.0# instance T creates an instance property of ' Myversion ' test.myversion    ## Output 3.0,t access to its own instance properties ##

However, when class properties are variable, things are different.

test.x={‘Myversion‘:‘1.0 "} # add a new class property to the test class test.x #< Span style= "COLOR: #008000" To access the property output in class Space {' Myversion ': ' 1.0 '}t.x # Use instance space to access the property output {' Myversion ': ' 1.0 '}t.x[ '  Myversion "]=" 2.0 '  t.x #  output {' myversion ': ' 2.0 '}test.x #  output {' myversion ': ' 2.0 '} # Update operation for instance T takes effect on class properties del t.x # error: t instance has no attribute ' x '     /span>                

Python Learning: Python Object-oriented (2)

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.