The best Python object-oriented Tutorial In 2024, In this tutorial you can learn Object-Oriented Technology Overview,Create class,Create an instance of an object,Access Properties,Python built-in class attribute,python object is destroyed (garbage collection),Class inheritance,Method overrides,Foundation overloaded methods,Operator Overloading,Class attributes and methods,
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.
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.
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
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)
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:
hasattr(emp1, 'age') # 如果存在 'age' 属性返回 True。 getattr(emp1, 'age') # 返回 'age' 属性的值 setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8 delattr(empl, 'age') # 删除属性 'age'
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>}
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.
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,
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): // /en. 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:
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, /en.]): '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 /en/en. class B: # 定义类 B /en/en. class C(A, B): # 继承类 A 和 B /en/en.
You can use issubclass () or isinstance () method to detect.
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:
调用子类方法
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 /en.] ) 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) |
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)
__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.
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_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
#!/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:
/en/en/en/en/en/en/en/en/en/en/en/en. print counter._JustCounter__secretCount
Execute the code above, execution results are as follows:
1 2 2 2