Latest web development tutorials

Python object-oriented

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.

Next, let's take a simple understanding of object-oriented under some basic features.


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:
   '类的帮助信息'   #类文档字符串
   class_suite  #类体

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:
   '所有员工的基类'
   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.

"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
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:
   '所有员工的基类'
   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

"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
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  # 添加一个 'age' 属性
emp1.age = 8  # 修改 'age' 属性
del emp1.age  # 删除 'age' 属性

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')    # 如果存在 'age' 属性返回 True。
getattr(emp1, 'age')    # 返回 'age' 属性的值
setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8
delattr(empl, 'age')    # 删除属性 '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 (comprising 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:
   '所有员工的基类'
   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__: 所有员工的基类
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0x10a939c80>, 'empCount': 0, 'displayEmployee': <function displayEmployee at 0x10a93caa0>, '__doc__': '\xe6\x89\x80\xe6\x9c\x89\xe5\x91\x98\xe5\xb7\xa5\xe7\x9a\x84\xe5\x9f\xba\xe7\xb1\xbb', '__init__': <function __init__ at 0x10a939578>}

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      # 创建对象  <40>
b = a       # 增加引用, <40> 的计数
c = [b]     # 增加引用.  <40> 的计数

del a       # 减少引用 <40> 的计数
b = 100     # 减少引用 <40> 的计数
c[0] = -1   # 减少引用 <40> 的计数

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 destroyed, when the object is no longer being 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, "销毁"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # 打印对象的id
del pt1
del pt2
del pt3

Examples of the above results are as follows:

3083401324 3083401324 3083401324
Point 销毁

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:        # 定义父类
   parentAttr = 100
   def __init__(self):
      print "调用父类构造函数"

   def parentMethod(self):
      print '调用父类方法'

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

   def getAttr(self):
      print "父类属性 :", Parent.parentAttr

class Child(Parent): # 定义子类
   def __init__(self):
      print "调用子类构造方法"

   def childMethod(self):
      print '调用子类方法 child method'

c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法
c.getAttr()          # 再次调用父类的方法

The above code is executed as follows:

调用子类构造方法
调用子类方法 child method
调用父类方法
父类属性 : 200

You can inherit multiple classes

class A:        # 定义类 A
.....

class B:         # 定义类 B
.....

class C(A, B):   # 继承类 A 和 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:        # 定义父类
   def myMethod(self):
      print '调用父类方法'

class Child(Parent): # 定义子类
   def myMethod(self):
      print '调用子类方法'

c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法

Execute the above code output results are as follows:

调用子类方法

Foundation overloaded methods

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

No. The method, described simply call &
1 __init__ (self [, args ...] )
Simply call the constructormethod:obj = className (args)
2 __del __ (self)
Destructors, delete an object simple methodcall:dell obj
3 __repr __ (self)
Conversion of the form for the interpreter to read a simple methodcall:repr (obj)
4 __str __ (self)
For the value into a form suitable for human reading a simple methodcall:str (obj)
5 __cmp__ (self, x)
Object relatively simple methodcall: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  # 私有变量
	publicCount = 0    # 公开变量

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

counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
print counter.__secretCount  # 报错,实例不能访问私有变量

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 <module>
    print counter.__secretCount  # 报错,实例不能访问私有变量
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