[Python] (X) object-oriented programming

1. Object-oriented preamble

Python from the beginning of the design is already an object-oriented language, and as such, create a class and objects in Python is easy.

Then first take a brief understanding of some basic features of object-oriented lower.

  • Class (Class): used to describe a collection of objects having the same properties and methods. It defines the set of properties and methods common to each object. Objects are instances of classes.
  • Class variables : Class variables are common throughout the instantiated object. And class variables defined outside the body of the function in the class. Class variables are typically not used as instance variables.
  • Data members : class variables or instance variables for processing data related to the class and object instance.
  • Method overloading : If you can not meet the needs of the subclass inherits from a parent class, can be rewritten, this process is called covering methods (override), also known as method overloading.
  • Examples of variables : variables defined in the process, only the role of the current instance of the class.
  • 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 treated. For example, there is such a design: the object type is derived from a Dog Animal class, which is an analog "is a (is-a)" relationship (FIG embodiment, an Animal Dog).
  • Instantiate : create an instance of a class, the specific object class.
  • Method : function defined in the class.
  • Object : a data structure example defined by the class. Objects include two data members (instance variables and class variables) and methods.

2. Create a class

Create a class

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

class ClassName:
   '类的帮助信息'   #类文档字符串
   class_suite  #类体

Help class can be viewed by ClassName .__ doc__.

class_suite a class member, method, data attributes.

Create an instance of the class

The following is a simple Python class instance:

#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 variable, its value will be shared between all instances of this class. You can access internal use Employee.empCount in class or outside class.
  • A first method __init __ () method is a special method, constructor, or class initialization method is called when an instance of the class the method is called to create the
  • Examples of self on behalf of the class, self-defined class when the method must be some, although not necessarily the appropriate parameters passed when calling.

Examples of representatives of the class of self, rather than the class

Method in class only one specific difference from ordinary functions - they must have an extra first parameter name, as is customary its name is self.

class Test:
    def prt(self):
        print(self)
        print(self.__class__)
t = Test()
t.prt()

The above examples Implementation of the results:

<__main__.Test instance at 0x10d066878>
__main__.Test

Can clearly be seen from the results of the implementation, Self represents the instance of the class, representative of the address of the current object, and points to the class self.class.

Create an instance of an object

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

"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 5000)

Access Properties

You can use dot (.) To access the object's properties. Access class variables with the name of the class as follows:

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

Complete example

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

Output:

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 property use the following functions:

  • getattr (obj, name [, default]): access target property.
  • hasattr (obj, name): Check for a property.
  • setattr (obj, name, value): Set a property. If the property does not exist, it creates a new property.
  • delattr (obj, name): Delete property.
hasattr(emp1, 'age')    # 如果存在 'age' 属性返回 True。
getattr(emp1, 'age')    # 返回 'age' 属性的值
setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8
delattr(empl, 'age')    # 删除属性 'age'

Built-in class attribute

  • dict : class attributes (including a dictionary, the data class attribute composition)
  • DOC : Class documentation strings
  • name : class name
  • Module1 : where the definition of class module (the full name of the class is the ' main .className', if introduced in a class module mymod, then className. Module1 equal mymod)
  • bases : All the elements constituting the parent class (in tuple contains all of the parent classes)

Examples are as follows:

#coding=utf-8
#!/usr/bin/python

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__

Output:

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>}

3. inherited class

inherit

One of the major benefits of object-oriented programming brings is to reuse code reuse to achieve this, one way is through the inheritance mechanism. Inheritance can fully understand the relationship between types and subtypes into classes.

Caveats: 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, in the tuple specified.

In python inherits some of the features:

  • 1: In the following structure (Cheng Zhongji class of the init () method) is not automatically invoked, it takes a special person to call in the construction of its derived class.
  • 2: when the method is called a base class, the class name prefix need to add the base class, and the need to bring the self parameter variables. You do not need to bring self parameters different from the ordinary function calls in the class
  • 3: Python always first find the corresponding type of method, corresponding method if it can not find in a derived class, it began to look one by one to the base class. (First find method call in this class, the base class can not be found before going to look for).

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, after inheriting the base class list with the class name, as follows:

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

Examples are as follows:

#coding=utf-8
#!/usr/bin/python

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()          # 再次调用父类的方法

Output:

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

May inherit multiple classes, examples are as follows:

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

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

class C(A, B):   # 继承类 A 和 B
.....

It may be used issubclass () or the isinstance () method to detect.

  • issubclass (): boolean function to determine 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 instance of the object class Class a Class or subclass return true

Method overrides

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

Examples are as follows:

#coding=utf-8
#!/usr/bin/python

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

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

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

Output:

调用子类方法

Method overloading

The following table lists some common functions can be overloaded in their classes:

No. The method, described simply call &
1 the init (Self [, args ...]) constructor method call to a simple: obj = className (args)
2 del (Self) destructor method call to a simple method for deleting an object: del obj
3 the repr (Self) into a simple form for the interpreter calls the read method: the repr (obj)
4 STR (Self) for values were converted to a form suitable for human reading simple call method: STR (obj)
5 cmp (Self, the X-) objects relatively simple method call: cmp (obj, the 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

Output:

Vector(7,8)

4. The class attributes and methods

  • Class private property: __private_attrs : two begins with an underscore, stating that the property is private and can not be used in class or direct access to the outside. When used in the interior of the method class Self .__ private_attrs .

  • Method class: within the class, the def keyword can be defined as a class method, and is generally different function definitions, methods must include the class parameter self, and as the first parameter

  • Private class methods: __private_method : two begins with an underscore, the method is declared as a private method can not be called in class to the outside. Call within the class of self .__ private_methods

Examples are as follows:

#coding=utf-8
#!/usr/bin/python
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  # 报错,实例不能访问私有变量

Output:

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 instantiated allowed to access private data, but you can use object._className__attrName access attributes, replace the last line of code above the code following code:

.........................
print counter._JustCounter__secretCount

The above code is executed, execution results are as follows:

1
2
2
2

Single underline, double underline, double underline head and tail description

  • foo : a special method is defined, system-defined names generally similar to the init () and the like.
  • _foo: starting with single underlined is protected types of variables, namely the protection type can only allow it to itself and the subclass access, can not be used from module import *
  • __foo: double underline indicates the type of private (private) variables can only be allowed to visit the class itself.
Published 246 original articles · won praise 121 · views 10000 +

Guess you like

Origin blog.csdn.net/BeiisBei/article/details/104044003
Recommended