Python object-oriented

Source: Internet
Author: User
Python has been an object-oriented language since its design. as a result, it is easy to create a class and object in Python. This section describes Python object-oriented programming in detail. Python has been an object-oriented language since its design. as a result, it is easy to create a class and object in Python. This section describes Python object-oriented programming in detail.

If you have never been familiar with object-oriented programming languages before, you may need to first understand some basic features of object-oriented languages and form a basic object-oriented concept in your mind, this helps you learn Python object-oriented programming more easily.

Next, let's take a look at some basic features of object-oriented systems.

Introduction to object-oriented technology

Class: a set of objects with the same attributes and methods. It defines the attributes and methods shared by each object in the set. The object is a class instance.

Class variables: class variables are public in the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are generally not used as instance variables.

Data member: class variables or instance variables are used to process data related to the class and its instance objects.

Method overload: If the method inherited from the parent class cannot meet the requirements of the subclass, you can rewrite it. this process is called override, or method overload.

Instance variable: a variable defined in the method. it only applies to the class of the current instance.

Inheritance: a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where a Dog-type object is derived from the Animal class, which simulates the relationship "is a (is-a)" (example diagram, Dog is an Animal ).

Instantiation: creates an instance of a class and a specific object of the class.

Method: The function defined in the class.

Object: a data structure instance defined by a class. The object includes two data members (class variables and instance variables) and methods.

Create class

Use the class statement to create a new class. the class is followed by the class name and ends with a colon, as shown in the following example:

Class ClassName:

'Optional class documentation string' # class document string

Class_suite # class body

Class help information can be viewed through ClassName. _ doc.

Class_suite consists of class members, methods, and data attributes.

Instance

The following is a simple Python class instance:

Class Employee:

'Common base class for all employees'

EmpCount = 0

Def _ init _ (self, name, salary ):

Self. name = name

Self. salary = salary

Employee. empCount + = 1

Def displayCount (self ):

Print "Total Employee % d" % Employee. empCount

Def displayEmployee (self ):

Print "Name:", self. name, ", Salary:", self. salary

The empCount variable is a class variable whose values are shared among all instances of the class. You can use Employee. empCount to access the internal or external classes.

The first method _ init _ () is a special method called a class constructor or initialization method, this method is called when an instance of this class is created.

Create an instance object

To create an instance of a class, you can use the class name and use the _ init _ method to accept parameters.

"This wocould create first object of Employee class"

Emp1 = Employee ("Zara", 2000)

"This wocould create second object of Employee class"

Emp2 = Employee ("Manni", 5000)

Access attributes

You can use vertex (.) to access the attributes of an object. Use the following class name:

Emp1.displayEmployee ()

Emp2.displayEmployee ()

Print "Total Employee % d" % Employee. empCount

Complete instance:

#! /Usr/bin/python

Class Employee:

'Common base class for all employees'

EmpCount = 0

Def _ init _ (self, name, salary ):

Self. name = name

Self. salary = salary

Employee. empCount + = 1

Def displayCount (self ):

Print "Total Employee % d" % Employee. empCount

Def displayEmployee (self ):

Print "Name:", self. name, ", Salary:", self. salary

"This wocould create first object of Employee class"

Emp1 = Employee ("Zara", 2000)

"This wocould create second object of Employee class"

Emp2 = Employee ("Manni", 5000)

Emp1.displayEmployee ()

Emp2.displayEmployee ()

Print "Total Employee % d" % Employee. empCount

The output result is as follows:

Name: Zara, Salary: 2000

Name: Manni, Salary: 5000

Total Employee 2

You can add, delete, and modify the attributes of a class as follows:

Emp1.age = 7 # Add an 'age' attribute

Emp1.age = 8 # Modify the 'age' attribute

Del emp1.age # Delete the 'age' attribute

You can also use the following functions to access attributes:

Getattr (obj, name [, default]): the attribute of the access object.

Hasattr (obj, name): check whether an attribute exists.

Setattr (obj, name, value): sets an attribute. If the property does not exist, a new property is created.

Delattr (obj, name): deletes an attribute.

Hasattr (emp1, 'age') # returns True if the 'age' property exists.

Getattr (emp1, 'age') # return the value of the 'age' attribute

Setattr (emp1, 'age', 8) # add the attribute 'age' with a value of 8

Delattr (empl, 'age') # delete attribute 'age'

Python built-in class attributes

_ Dict _: class attributes (including a dictionary consisting of class data attributes)

_ Doc _: document string of the class

_ Name __: class name

_ Module __: module where the class definition is located (the full name of the class is '_ main __. classname'. if the class is located in mymod of an import module, then className. _ module _ equals to mymod)

_ Bases _: elements of all parent classes of the class (including tuples consisting of all parent classes)

The Python built-in class property Call example is as follows:

#! /Usr/bin/python

Class Employee:

'Common base class for all employees'

EmpCount = 0

Def _ init _ (self, name, salary ):

Self. name = name

Self. salary = salary

Employee. empCount + = 1

Def displayCount (self ):

Print "Total Employee % d" % Employee. empCount

Def displayEmployee (self ):

Print "Name:", self. name, ", Salary:", self. salary

Print "Employee. _ doc __:", Employee. _ doc __

Print "Employee. _ name __:", Employee. _ name __

Print "Employee. _ module __:", Employee. _ module __

Print "Employee. _ bases __:", Employee. _ bases __

Print "Employee. _ dict __:", Employee. _ dict __

The output result is as follows:

Employee. _ doc __: Common base class for all employees

Employee. _ name __: Employee

Employee. _ module __: _ main __

Employee. _ bases __:()

Employee. _ dict __:{ '_ module _': '_ main _', 'displaycount ':

, 'Empcount': 2,

'Displayemployee ': ,

'_ Doc _': 'common base class for all employees ',

'_ Init __': }

Python object destruction (garbage collection)

Like the Java language, Python uses the reference count simple technology to track objects in memory.

In Python, the number of references of all objects in use is recorded.

An internal trace variable is called a reference counter.

When an object is created, a reference count is created. when this object is no longer needed, that is, when the reference count of this object is changed to 0, it is recycled. However, the recycle object is not "immediate". at the right time, the interpreter recycles the memory space occupied by the spam object.

A = 40 # create an object <40>

B = a # Add reference, <40> count

C = [B] # Add reference. <40> count

Del a # reduce the reference count <40>

B = 100 # reduce the reference count <40>

C [0] =-1 # reduce the reference count <40>

The recycling mechanism not only applies to objects with 0 reference counts, but also can handle cyclic references. Loop reference refers to the mutual reference between two objects, but no other variables reference them. In this case, it is not enough to count with reference only. The Python garbage collector is actually a reference counter and a circular garbage collector. As a supplement to reference counting, the garbage collector will also pay attention to objects with a large total allocation volume (and those that are not destroyed by reference counting. In this case, the interpreter pauses and tries to clear all the loops that are not referenced.

Instance

Destructor _ del _ ,__ del _ is called when the object disappears. when the object is no longer used, run the __del _ method:

#! /Usr/bin/python

Class Point:

Def _ init (self, x = 0, y = 0 ):

Self. x = x

Self. y = y

Def _ del _ (self ):

Class_name = self. _ class _. _ name __

Print class_name, "destroyed"

Pt1 = Point ()

Pt2 = pt1

Pt3 = pt1

Print id (pt1), id (pt2), id (pt3) # print the object id

Del pt1

Del pt2

Del pt3

The running result of the above instance is as follows:

3083401324 3083401324 3083401324

Point destroyed

Note: You usually need to define a class in a separate file,

Class inheritance

One of the main benefits of object-oriented programming is code reuse. one of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be fully understood as the relationship between types and subtypes between classes.

Note: inherited syntax class derived class name (base class name )://... in the base class name writing brackets, the basic class is specified in the tuples when the class is defined.

Some features of inheritance in python:

1: The Construction (_ init _ () method) of the base class in the inheritance class will not be automatically called. it needs to be called in the construction of its derived class.

2: When calling a base class method, you must add the base class name prefix and the self parameter variable. Unlike calling a common function in a class, the self parameter is not required.

3: Python always first looks for the corresponding type of method. if it cannot find the corresponding method in the derived class, it starts to look for it one by one in the base class. (Search for the called method in this class before finding it in the base class ).

If more than one class is listed in the inheritance tuples, it is called "multi-inheritance ".

Syntax:

The declaration of a derived class is similar to that of its parent class. the list of inherited base classes follows the class name, as shown below:

Class SubClassName (ParentClass1 [, ParentClass2,...]):

'Optional class documentation string'

Class_suite

Instance:

#! /Usr/bin/python

Class Parent: # define parent class

ParentAttr = 100

Def _ init _ (self ):

Print "Calling parent constructor"

Def parentMethod (self ):

Print 'calling parent method'

Def setAttr (self, attr ):

Parent. parentAttr = attr

Def getAttr (self ):

Print "Parent attribute:", Parent. parentAttr

Class Child (Parent): # define child class

Def _ init _ (self ):

Print "Calling child constructor"

Def childMethod (self ):

Print 'calling child method'

C = Child () # instantiate a subclass

C. childMethod () # Call the subclass method

C. parentMethod () # call the parent class method

C. setAttr (200) # call the method of the parent class again

C. getAttr () # call the method of the parent class again

The code execution result is as follows:

Calling child constructor

Calling child method

Calling parent method

Parent attribute: 200

You can inherit multiple classes

Class A: # define your class

.....

Class B: # define your calss B

.....

Class C (A, B): # subclass of A and B

.....

You can use the issubclass () or isinstance () method for detection.

Issubclass ()-Boolean function determines whether a class is a subclass or descendant class of another class. Syntax: issubclass (sub, sup)

The Boolean function of isinstance (obj, Class) returns true if obj is an instance object of the Class or an instance object of a Class subclass.

Overload method

If the features of your parent class method cannot meet your needs, you can reload the methods of your parent class in the subclass:

Instance:

#! /Usr/bin/python

Class Parent: # define the Parent class

Def myMethod (self ):

Print 'calling parent method'

Class Child (Parent): # define a subclass

Def myMethod (self ):

Print 'calling child method'

C = Child () # Subclass instance

C. myMethod () # Subclass call the overload method

The output result is as follows:

Calling child method

Basic overload method

The following table lists some common functions that can be rewritten in your own class:

Serial Number

Method, description & simple call

1 _ init _ (self [, args...])
Constructor
Simple call method: obj = className (args)

2 _ del _ (self)
STRUCTURE method to delete an object
Simple call method: dell obj

3 _ repr _ (self)
Converted to the form for the interpreter to read
Simple call method: repr (obj)

4 _ str _ (self)
Used to convert a value into a form suitable for reading.
Simple call method: str (obj)

5 _ cmp _ (self, x)
Object comparison
Simple call method: cmp (obj, x)

Operator overload

Python also supports operator overloading. The example is as follows:

#! /Usr/bin/python

Class Vector:

Def _ init _ (self, a, B ):

Self. a =

Self. B = B

Def _ str _ (self ):

Return 'vector (% d, % d) '% (self. a, self. B)

Def _ add _ (self, other ):

Return Vector (self. a + other. a, self. B + other. B)

V1 = Vector (2, 10)

V2 = Vector (5,-2)

Print v1 + v2

The code execution result is as follows:

Vector (7,8)

Hide data

It is easy to implement data hiding in python. you do not need to add any keywords in front of the class variable name or member function. you only need to add two underscores in front of the class variable name or member function to implement the data hiding function, for an instance of a class, its variable name and member function cannot be used, and its inherited class is also hidden, the inherited class can define the same variable name or member function name without causing name conflict. Instance:

#! /Usr/bin/python

Class JustCounter:

_ SecretCount = 0

Def count (self ):

Self. _ secretCount + = 1

Print self. _ secretCount

Counter = JustCounter ()

Counter. count ()

Counter. count ()

Print counter. _ secretCount

Python changes the name to include the class name:

1

2

Traceback (most recent call last ):

File "test. py", line 12, in

Print counter. _ secretCount

AttributeError: JustCounter instance has no attribute '_ secretCount'

Python does not allow instantiated classes to access hidden data, but you can use object. _ className _ attrName to access the property and replace the following code with the last line of code of the above code:

.........................

Print counter. _ JustCounter _ secretCount

Run the preceding code and the execution result is as follows:

1

2

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.