Study Notes Object-oriented Python -Python

 

Object-Oriented Technology Overview

  • 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 the associated data processing and class instance object.
  • Method overrides: 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 the overriding method.
  • Local variables: variables defined in the process, only the role of the current instance of the class.
  • Examples of variables: the class declaration, the attribute variable is represented. This variable is called an instance variable, but the statement is in addition to other members of the class methods inside the class declaration.
  • 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.

Create a class

Use the class statement to create a new class, after class is the class name and a colon at the end:

class ClassName:
   '类的帮助信息'   #类文档字符串
   class_suite  #类体由类成员,方法,数据属性组成。

Help class can be viewed by ClassName .__ doc__.

Examples

The following is a simple example Python class:

Examples

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Employee:
   '所有员工的基类' #类文档字符串
   empCount = 0    #类变量——所有实例之间共享
 
   def __init__(self, name, salary): #构造函数或初始化方法
      self.name = name               #self 代表类的实例;定义时必须存在,调用时不存在
      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 in this class is shared among all instances . You can access internal use Employee.empCount in class or outside class .

  • A first method __init __ () method is a special method, referred to as a class constructor or initialization method , the method is called when an instance of the class when

  • Examples of self on behalf of the class, self-defined classes when the method is to be there, although the corresponding parameter does not have to pass the call.

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

Method class ordinary functions only a special distinction - they must have an extra first argument name , by convention its name is self (replaceable, needs to be consistent).

class Test:
    def prt(self):
        print(self)    #运行结果:<__main__.Test instance at 0x10d066878>
        print(self.__class__)    #运行结果:__main__.Test
 
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  self .__ class__ points to the class .

self is not a python keyword, we can also put him into runoob normal execution of:

Examples

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

The above examples Implementation of the results:

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

Create an instance of an object

Examples of a similar class function call Python

Below using the class name Employee to instantiate and __ (self, name, salary) method receives parameters __init.

"Create first object class Employee" 
emp1 = Employee ( "Zara", 2000) 
"Employee class to create a second object" 
EMP2 = Employee ( "Manni", 5000)

Access Properties

Examples

#!/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
print "调用(实例.方法)emp1.displayCount():";emp1.displayCount()

Performing the above code output results are as follows:

Name :  Zara , Salary:  2000
Name :  Manni , Salary:  5000
Total Employee 2
调用(实例.方法)emp1.displayCount():
Total Employee 2

In a similar call directly add, delete, modify the properties of the class:

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') # If 'age' presence property returns True. getattr (emp1, 'age') # Returns 'age' attribute value setattr (emp1, 'age', 8) # add attributes 'age' is 8 delattr (emp1, 'age') # remove attributes 'age'


Python built-in class attribute

  • __dict__: class attributes (including a dictionary, the data class attribute composition)
  • __doc__: Class documentation strings
  • __name__: class name
  • __module__: where the class definition module (the full name of the class is '__main __ className.' (generally a __main__), if introduced in a class module mymod, then className .__ module__ equal mymod)
  • __bases__: All the elements constituting the parent class (a tuple contains all of the parent classes)

Built call Python class attribute examples are as follows:

Examples

#!/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__

Performing 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)

Reference count - tracking and garbage inside Python recording how many references have all active objects.

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 (reference count reaches zero the object), it is garbage collected.

But the recovery is not "immediately" by the interpreter at the appropriate time, will take up memory space garbage objects recovered .

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 a reference count of the object 0, the same can also handle the case of circular references. Circular reference means that two objects refer to each other, but there is 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 garbage collector. As a supplementary reference counting garbage collector will pay attention to the total amount allocated large object (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 used, __ del__ method of operating (Python 2.X):

Example (Python 2.X)

#!/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 destroyed

Class inheritance

One way to achieve code reuse through inheritance.

Create a new class by inheriting is called a subclass or derived class ,

Inherited class is called a base class , a parent class or superclass .

Inheritance syntax

class derived class name (the base class name) 
    ...

In python inherits some of the features:

  • 1, if necessary in the parent class constructor to subclass
  • 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. Does not need to bring self parameters except that the ordinary function call category
  • 3, Python always find the corresponding first type of process, subclass -> 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, after inheriting the base class list with the class name, as follows:

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

Examples

#!/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 '调用子类方法'
 
c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
c.getAttr()          # 再次调用父类的方法 - 获取属性值

Code executes the above results are as follows:

Subclass constructor method call 
to call sub-class method 
calls the method of the parent class 
the parent class attributes: 200

You can inherit multiple classes

class A: # define class A 
..... 

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

class C (A, B): A and class B inherits # 
.....

You can use issubclass () or 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 returns true.

Method override ( inherited methods)

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

Example:

Examples

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Parent:        # 定义父类
   def myMethod(self):
      print '调用父类方法'
 
class Child(Parent): # 定义子类
   def myMethod(self):  # 子类重写方法
      print '调用子类方法'
 
c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法

Performing the above code output results are as follows:

Calls the subclass method

Basis 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 ...]
) constructor
simply call a method:  obj = className (args)
2 __del __ (self)
destructor, deleting an object
simple method call:  del obj
3 __repr __ (self)
converted to the form read by the interpreter for
a simple method call:  the repr (obj)
4 __str __ (self)
is used to translate the value suitable for both human readable
simple call method:  STR (obj)
5 __cmp__ (self, x)
target relatively
simple method call:  cmp (obj, the X-)

Operator overloading (for existing operators)

Python also supports operator overloading, examples are as follows:

Examples

#!/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)

   def __sub__(self, other):
      return Vector(self.a - other.a, self.b - other.b)

   def __mul__(self, other):
      return Vector(self.a * other.a, self.b * other.b) 

v1 = Vector(2,10)
v2 = Vector(5,-2)

print v1 + v2
print v1 - v2
print v1 * v2

Code executes the above results are as follows:

Vector(7,8)
Vector(-3,12)
Vector(10,-20)

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

  • __foo__ : a special method is defined, system-defined names generally similar __init __ () or 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 access the class itself (access method inside the class: self .__ foo).

Class attributes and methods

Class of private property

__private_attrs : two begins with an underscore, stating that the property is private , can not be used or accessed directly from outside the class . When used in the interior of the method class  Self .__ private_attrs .

Methods of the class

Within the class, the use of  def  keyword can be defined as a class method, different from the general definition of the function, class method must contain parameters self, and as the first parameter.

def method(self[,arge1[,arge2···]])

Private methods of class

__private_method : two begins with an underscore, the method is declared as a private method, external calls can not be in class. Call within the class of  self .__ private_methods

def self.__private_method(self[,arge1[,arge2···]])

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 Last Call): 
  File "the test.py", Line. 17, in <Module1> 
    Print error counter .__ secretCount #, instances can not access the private variable 
AttributeError: JustCounter instance has no attribute ' __secretCount'

Python does not allow instantiated class ( instances ) to access private data, but you can use  object._className__attrNameobject name class name __ ._ private property name  ) to access the properties, refer to the following examples:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Runoob:
    __site = "www.runoob.com"

runoob = Runoob()
print runoob._Runoob__site

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

www.runoob.com
Published 19 original articles · won praise 0 · Views 805

Guess you like

Origin blog.csdn.net/weixin_44151772/article/details/104044387