Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Python object-oriented programming     - Linux system last command usage (Linux)

- 256 with rich colors decorate your terminal (Linux)

- After the first remote installation GlassFish Web to remotely access their back office management system error solution appears (Server)

- Linux upgrade Glibc (Linux)

- Atlassian Linux Shell Scripting the confluence remote backup methods (Linux)

- Detailed iptables (Linux)

- DOM event handlers add notes (Programming)

- Use $ BASH ENV variable to mention the right way under Linux (Linux)

- Linux based serial programming (Programming)

- SA weak password security system of the security risks posed (Linux)

- Performance comparison Fibonacci recursive and non-recursive (Programming)

- Oracle 11g RMAN virtual private directory (Database)

- Android Service service applications and the phone SMS Listener Listener (Programming)

- Android Service Lifecycle and usage (Programming)

- RedHat Redis Linux installation (Database)

- Linux crontab command format example (Linux)

- grep command Series: How to Use the grep command in Linux / UNIX (Linux)

- How to install Docker and basic usage on Ubuntu 15.04 (Server)

- Use LVM partition on Ubuntu and easily adjust the snapshot (Linux)

- The Gitlab migrated to Docker container (Server)

 
         
  Python object-oriented programming
     
  Add Date : 2017-01-08      
         
         
         
  Python has been designed from the start is an object-oriented language, and as such, create a class and objects in Python is very easy. This section we will detail the object-oriented programming in Python.

If you have not been exposed to object-oriented programming language, then you may need to first understand some of the basic features of object-oriented languages, formed in the mind inside a basic concept of object-oriented, which helps you more easily learn the Python object-oriented programming.

Object-Oriented Technology Overview

Class (Class): used to describe the collection have the same properties and methods of objects. It defines a set of properties and methods common to each object. Objects are instances of classes.
Class variables: class variables is common throughout the instantiated object. Class variables defined and outside the function in the class in. Class variables not normally used as instance variables.
Data members: class variables or instance variables for the associated data processing classes and instance objects.
Overrides: If you can not meet the needs of a subclass inherits from the parent class method, it can be rewritten, a process called overlay method (override), also known as the overriding method.
Examples of variables: variables defined in the method, only the role of the class of the current instance.
Inheritance: That is a derived class (derived class) inherits the base class (base class) fields and methods. Inheritance also allows a derived class object as a base class object treat. For example, there is such a design: an object type that is derived from a Dog Animal class, which is an analog "is a (is-a)" relationship (Fig example, is a Dog Animal).
Instantiate: create an instance of a class, the specific object class.
Methods: The class-defined functions.
Object: data structure instance through the class definition. Data objects include two members (class and instance variables) and methods.
Create class

Use the class statement to create a new class, after class, and the class name ends with a colon, the following examples:

class ClassName:
   'Type of help' Issue # string
   class_suite # class body
Help class can be viewed by ClassName .__ doc__.

class_suite composed of members of the class, method, data attributes.

Examples

The following is a simple Python class instance:

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

class Employee:
   'All employees of the base class'
   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
empCount variable is a class variable, its value will be shared between all instances of this class. You can use Employee.empCount access within the class or outside class.
The first method __init __ () method is a special method, constructor or class initialization method is called when creating an instance of this class will call the method
Create an instance of an object

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

"Create Employee Class object"
emp1 = Employee ( "Zara", 2000)
"Create Employee class second object"
emp2 = Employee ( "Manni", 5000)
Access Properties

You can use the dot (.) Property to access the object. Accessing a class variable with the name of the class as follows:

emp1.displayEmployee ()
emp2.displayEmployee ()
print "Total Employee% d"% Employee.empCount
Complete example:

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

class Employee:
   'All employees of the base class'
   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

"Create Employee Class object"
emp1 = Employee ( "Zara", 2000)
"Create Employee class second object"
emp2 = Employee ( "Manni", 5000)
emp1.displayEmployee ()
emp2.displayEmployee ()
print "Total Employee% d"% Employee.empCount
Execute the above code output results are as follows:

Name: Zara, Salary: 2000
Name: Manni, Salary: 5000
Total Employee 2
You can add, delete, modify the properties of the class as follows:

emp1.age = 7 # add an 'age' property
emp1.age = 8 # modify 'age' property
del emp1.age # delete 'age' property
You can also access the properties use the following functions:

getattr (obj, name [, default]): property access objects.
hasattr (obj, name): Check whether there is an attribute.
setattr (obj, name, value): set a property. If the property does not exist, create a new property.
delattr (obj, name): delete attributes.
hasattr (emp1, 'age') # If there 'age' property returns True.
getattr (emp1, 'age') # returns 'age' of the value of the property
setattr (emp1, 'age', 8) # add the attribute 'age' is 8
delattr (empl, 'age') # delete property 'age'
Python built-in class attribute

__dict__: attributes of the class (including a dictionary, the data attribute class composition)
__doc__: document string class
__name__: class name
__module__: module where the class definition (the full name is '__main __ className.', if the class is located in an imported module mymod, then className .__ module__ equal mymod)
__bases__: All classes of the parent element (included in a parent class consisting of all tuples)
Python calls the built-in class attribute examples are as follows:

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

class Employee:
   'All employees of the base class'
   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__
Execute the above code output results are as follows:

Employee .__ doc__: the base class for all employees
Employee .__ name__: Employee
Employee .__ module__: __main__
Employee .__ bases__: ()
Employee .__ dict__: { '__module__': '__main__', 'displayCount': , 'empCount': 0, 'displayEmployee': , '__doc__': '\ xe6 \ x89 \ x80 \ xe6 \ x9c \ x89 \ xe5 \ x91 \ x98 \ xe5 \ xb7 \ xa5 \ xe7 \ x9a \ x84 \ xe5 \ x9f \ xba \ xe7 \ xb1 \ xbb ',' __init__ ': }
python object is destroyed (garbage collection)

Like the Java language, Python uses reference counting this simple technique to track objects in memory.

In Python internal record of all the objects using the respective numbers of references.

An internal tracking variables, called a reference counter.

When an object is created, it creates a reference count, when the object is no longer needed, that is to say, a reference to the object count becomes 0, it is garbage collected. But the recovery is not "immediately" by the interpreter at the appropriate time, the garbage objects occupy memory space reclamation.

a = 40 # Create Object <40>
b = a # increase the reference, <40> count
c = [b] # increment the reference. <40> count

del a # decrements the reference <40> count
b = 100 # decrements the reference <40> count
c [0] = -1 # decrements the reference <40> count
 Garbage collection mechanism not only for the object reference count is 0, the same can also handle the case of circular references. It refers to a circular reference, two objects refer to each other, but no other variable references them. In this case, only the reference count is not enough. Python's garbage collector is actually a reference to a cycle counter and the garbage collector. As a supplementary reference counting garbage collector will pay attention to the total amount allocated large objects (and not counting those destroyed by reference). In this case, the interpreter will pause, trying to clean up all the unreferenced cycle.

Examples

Destructor __del__, __ del__ is called when the object is gone, when the object is no longer used, __ del__ method to run:

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

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
id print id (pt1), id (pt2), id (pt3) # print target
del pt1
del pt2
del pt3
Examples of the above results are as follows:

3083401324 3083401324 3083401324
Point destroyed
Note: Usually you need to define a class in a separate file,

Class inheritance

One of the major benefits of object-oriented programming is brought to reuse code reuse to achieve one of these is through the inheritance mechanism. Inherited completely understandable type and subtype relationship between classes into.

Caveat: Inheritance Syntax class derived class name (the base class name): // ... writing the base class name in brackets, when the base class is the class definition, among tuples specified.

In python succession of some of the features:

1: In the following configuration (__init __ () method) Cheng Zhongji class will not be automatically invoked, it requires specialized personally called in the constructor of its derived class.
2: When you call the base class method, you need to add the class name prefix of the base class, and the need to bring self parameter variables. Do not need to bring self parameter is different from the ordinary function call in the class
3: Python always first find the corresponding type of approach, if it can not find the corresponding method in a derived class, it began to look one by one to the base class. (First method calls to find in this class, only to find to find the base class).
If the column more than one class in the inheritance tuple, then it is called "multiple inheritance."

grammar:

Declaration of the derived class, similar to their parent class, then inherit the base class list with the class name, as follows:

class SubClassName (ParentClass1 [, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite
Example:

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

class Parent: # definition of the parent class
   parentAttr = 100
   def __init __ (self):
      print "call the parent class constructor"

   def parentMethod (self):
      print 'call the parent class method'

   def setAttr (self, attr):
      Parent.parentAttr = attr

   def getAttr (self):
      print "Parent class attributes:", Parent.parentAttr

class Child (Parent): # define subclasses
   def __init __ (self):
      print "call subclass constructors"

   def childMethod (self):
      print 'subclass method calls the child method'

c = Child () # instantiable subclass
c.childMethod () # call the subclass method
c.parentMethod () # call the parent class method
c.setAttr (200) # calls the parent class method again
c.getAttr () # call the parent class method again
The above code is executed as follows:

Call subclass constructors
Child method calls the subclass method
Call the parent class method
Parent class properties: 200
You can inherit multiple classes

class A: # definition of class A
.....

class B: # define a class B
.....

class C (A, B): # inherited classes A and B
.....
You can use issubclass () or isinstance () method to detect.

issubclass () - Boolean function to determine whether a class is a subclass of another class or descendant class syntax: issubclass (sub, sup)
isinstance (obj, Class) Boolean function if obj is an instance of an object class or instance object Class Class is a subclass returns true.
Method overrides

If the function you are the parent class method can not meet your needs, you can rewrite your parent class method in a subclass:

Example:

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

class Parent: # definition of the parent class
   def myMethod (self):
      print 'call the parent class method'

class Child (Parent): # define subclasses
   def myMethod (self):
      print 'call the subclass method'

c = Child () # subclass instance
c.myMethod () # call subclass override method
Execute the above code output results are as follows:

Call the subclass method
Foundation overloaded methods

The following table lists some of the common features that you can override in your class:

Reference method description & simple call
1 __init__ (self [, args ...])
Constructor
A simple method call: obj = className (args)
2 __del __ (self)
Destructor method, an object is deleted
A simple method call: dell obj
3 __repr __ (self)
Conversion of the form for the interpreter to read
A simple method call: repr (obj)
4 __str __ (self)
For the value is converted to a form suitable for human reading
A simple method call: str (obj)
5 __cmp__ (self, x)
Object Comparison
A simple method call: cmp (obj, x)
Operator Overloading

Python also supports operator overloading, examples are as follows:

#! / Usr / bin / python

class Vector:
   def __init __ (self, a, b):
      self.a = 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 above code execution results are as follows:

Vector (7,8)
Class attributes and methods

Private property class

__private_attrs: beginning two underscores stating that the property is private and can not be used or accessed directly in the class externally. self .__ private_attrs when used within a class method.

Class methods

In the terrestrial interior, use def keyword can be defined as a class method with the general definition of the different functions, class methods must include the parameter self, and as the first parameter

Private methods of class

__private_method: the first two underscore, the method is declared as private methods in the class can not call externally. Calls self .__ private_methods within the class

Examples

#! / Usr / bin / python
# - * - Coding: UTF-8 - * -

class JustCounter:
    __secretCount = 0 # private variable
    publicCount = 0 # public variables

    def count (self):
        self .__ secretCount + = 1
        self.publicCount + = 1
        print self .__ secretCount

counter = JustCounter ()
counter.count ()
counter.count ()
print counter.publicCount
print counter .__ secretCount # error, you can not access the private instance variable
Python by changing the name to include the name of the class:

1
2
2
Traceback (most recent call last):
  File "test.py", line 17, in
    print counter .__ secretCount # error, you can not access the private instance variable
AttributeError: JustCounter instance has no attribute '__secretCount'
Python is not allowed instantiated class access private data, but you can use object._className__attrName access attributes, the following code will replace the last line of code above the code:

.........................
print counter._JustCounter__secretCount
Execute the code above, execution results are as follows:

1
2
2
2
     
         
         
         
  More:      
 
- xCAT line installation on CentOS 6.X (Linux)
- Ubuntu 14.10 / 14.04 how to install Quick Start tool Mutate 2.2 (Linux)
- After installing Ubuntu 15.04, to do a few things (Linux)
- Java, extends and implements Usage (Programming)
- Subsequent binary search tree traversal sequence (Programming)
- CentOS 6.6 x64 Oracle Database 11gR2 RAC automated installation scripts (Database)
- Binary tree traversal recursive and non-recursive (cyclic) traversal achieve (Programming)
- ARP Linux-related operations (Linux)
- KVM virtualization of nested virtualization (Linux)
- Ceph performance optimization summary (v0.94) (Server)
- Deployment Kubernetes manage Docker example cluster on Ubuntu (Server)
- Orabbix binding Python send graphical reports (Linux)
- About AWR More Description (Database)
- Oracle local user login authentication fails ORA-01031 insufficient privileges (Database)
- ASM learning overview (Database)
- 20+ Best Practices article MySQL Performance Optimization (Database)
- Windows Desktop use VNC remote connect Linux (Linux)
- Install Kali Linux via PXE network (Linux)
- iSCSI + multipath achieve DM multipath storage (Server)
- Linux Task Scheduler (at, crontab) (Linux)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.