Home > Backend Development > Python Tutorial > Python object-oriented

Python object-oriented

高洛峰
Release: 2016-11-23 14:09:08
Original
999 people have browsed it

Python has been an object-oriented language from the beginning, and because of this, it is easy to create classes and objects in Python. In this chapter we will introduce object-oriented programming in Python in detail.

If you have not been exposed to object-oriented programming languages ​​before, you may need to first understand some basic features of object-oriented languages ​​and form a basic object-oriented concept in your mind, which will help you learn more easily. Object-oriented programming in Python.

Next, let’s briefly understand some basic characteristics of object-oriented.

Introduction to Object-Oriented Technology

Class (Class): Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes.

Class variables: Class variables are public throughout the instantiated object. Class variables are defined in the class and outside the function body. Class variables are generally not used as instance variables.

Data members: Class variables or instance variables are used to handle data related to the class and its instance objects.

Method overloading: If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method override, also known as method overloading.

Instance variables: Variables defined in methods only act on the class of the current instance.

Inheritance: That is, a derived class inherits the fields and methods of a base class. Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is such a design: an object of type Dog is derived from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).

Instantiation: Create an instance of a class, a specific object of the class.

Method: Function defined in the class.

Object: An instance of a data structure defined through a class. Objects include two data members (class variables and instance variables) and methods.

Create a class

Use the class statement to create a new class. After class is the name of the class and ends with a colon, as in the following example:

class ClassName:

'Optional class documentation string'#Class documentation character String

class_suite #Class body

The help information of the class can be viewed through ClassName.__doc__.

class_suite consists of class members, methods, and data attributes.

Example

The following is a simple Python class example:

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary ):

           self.name                                                                                                                                            self. %d" % Employee.empCount

def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

empCount variable is a class variable, its value will be in all of this class shared between instances. You can access it using Employee.empCount in inner class or outer class.

The first method __init__() method is a special method, called the constructor or initialization method of the class. This method will be called when an instance of this class is created

Create an instance object

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

"This would create first object of Employee class"

emp1 = Employee("Zara", 2000)

"This would create second object of Employee class"

emp2 = Employee("Manni", 5000)

Accessing properties

You can use the dot (.) to access the properties of an object. Access the class variable using the following class name:

emp1.displayEmployee()

emp2.displayEmployee()

print "Total Employee %d" % Employee.empCount

Full example:

#!/usr/bin/python

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

          self.name                                                                                                        self.O Print "Total Employee %D" %Employeee.empCount

defly DisplayemPloyee (Self):

Print "name:", seld.name, ", Self.salary

create first object of Employee class"

emp1 = Employee("Zara", 2000)

"This would create second object of Employee class"

emp2 = Employee("Manni", 5000)

emp1.displayEmployee()

emp2.displayEmployee()

print "Total Employee %d" % Employee.empCount

Execute the above code and the output result is as follows:

Name : Zara ,Salary: 2000

Name : Manni ,Salary: 5000

Total Employee 2

You can add, delete, modify the attributes of the class, as shown below:

emp1.age = 7 # Add an 'age' attribute

emp1.age = 8 # Modify the 'age' attribute

del emp1.age # Delete the 'age' attribute

You can also use the following function to access the attribute:

getattr(obj, name[ , default]): access the properties of the object.

hasattr(obj,name) : Check if an attribute exists.

setattr(obj,name,value): Set an attribute. If the property does not exist, a new property is created.

delattr(obj, name) : Delete attributes.

hasattr(emp1, 'age') # Return True if the 'age' attribute exists.

getattr(emp1, 'age') # Return the value of the 'age' attribute

setattr(emp1, 'age', 8) # Add the attribute 'age' with a value of 8

delattr(empl, 'age') # Delete the attribute 'age'

Python built-in class attributes

__dict__: attributes of the class (contains a dictionary, composed of data attributes of the class)

__doc__: documentation string of the class

__name__: class name

__module__: The module in which the class is defined (the full name of the class is '__main__.className'. If the class is located in an imported module mymod, then className.__module__ is equal to mymod)

__bases__: All parent class elements of the class (including As a tuple consisting of all parent classes)

Python built-in class attribute calling example is as follows:

#!/usr/bin/python

class Employee:

'Common base class for all employees'

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__

The output of executing the above code is as follows:

Employee.__doc__: Common base class for all employees

Employee.__name__: Employee

Employee.__module__: __main__

Employee.__bases__: ()

Employee.__dict__: {'__module__': '__main__', 'displayCount':

, 'empCount': 2,

'displayEmployee': ,

'__doc__': 'Common base class for all employees',

'__init__': }🎜🎜 🎜🎜 🎜🎜python Object destruction (garbage collection)🎜🎜Like the Java language, Python uses a simple technology called reference counting to track objects in memory. 🎜🎜Internally, Python records how many references each object in use has. 🎜🎜An internal tracking variable called a reference counter. 🎜

When an object is created, a reference count is created. When the object is no longer needed, that is, when the object's reference count becomes 0, it is garbage collected. However, recycling is not "immediate". The interpreter will recycle the memory space occupied by garbage objects at the appropriate time.

a = 40 # Create object <40>

b = a # Increase the count of <40>

c = [b] # Increase the reference. <40> Count of

del a       # Decrease the count of reference <40>

b = 100 # Decrease the count of reference <40>

c[0] = -1 # Decrease the count of reference <40>

The garbage collection mechanism not only targets objects with a reference count of 0, but can also handle circular references. A circular reference occurs when two objects refer to each other, but no other variable refers to them. In this case, reference counting alone is not enough. Python's garbage collector is actually a reference counter and a cyclic garbage collector. In addition to reference counting, the garbage collector also looks at objects that have been allocated a large amount (and those that have not been destroyed by reference counting). In this case, the interpreter will pause and try to clean up any unreferenced loops.

Instance

Destructor __del__, __del__ is called when the object disappears. When the object is no longer used, the __del__ method runs:

#!/usr/bin/python

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

print id(pt1), id(pt2), id(pt3) # Print object id

del pt1

del pt2

del pt3

The above example running results are as follows:

3083401324 308 3401324 3083401324

Point destroyed

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

Inheritance of class

One of the main benefits of object-oriented programming is the reuse of code, methods to achieve this reuse One is through the inheritance mechanism. Inheritance can be completely understood as the type and subtype relationship between classes.

Things to note: inheritance syntax class derived class name (base class name): //... The base class name is written in brackets. The base class is specified in the tuple when the class is defined.

Some features of inheritance in python:

1: In inheritance, the construction of the base class (__init__() method) will not be automatically called, it needs to be called specifically in the construction of its derived class.

2: When calling the method of the base class, you need to add the class name prefix of the base class, and you need to bring the self parameter variable. Different from calling ordinary functions in a class, you do not need to bring the self parameter

3: Python always first searches for the method of the corresponding type. If it cannot find the corresponding method in the derived class, it starts to go to the base class one by one. Find. (First look for the calling method in this class, and then look for it in the base class if you can't find it).

If more than one class is listed in the inheritance tuple, then it is called "multiple inheritance".

Syntax:

Declaration of derived classes, similar to their parent classes, with a list of inherited base classes following the class name, as follows:

class SubClassName (ParentClass1[, ParentClass2, ... :       # define parent class

    parentAttr = 100e DEF __init __ (Self):

Print "Calling Parent Constructor"

Def ParentMethod (Self):

Print 'Callling Parent Method'

DEF SELF, Attr):

Parent.parentAttr = attr

def getAttr(self):

print "Parent attribute:", Parent.parentAttr

classChild(Parent): #def __init__(self):

print "Calling child constructor"

def childMethod(self):

print 'Calling child method'

c =Child()             # Instantiate the subclass

c.childMethod()       # Call the method of the subclass

c.parentMethod()         # Call the method of the parent class

c.setAttr(200)                          Tc.getattr ()# The method of calling the parent class again

The above code execution results are as follows:

Calling Child Constructor

Calling Child Method

Calling Parent ATTRIBUTE: 200

You can inherit multiple classes

class A:         # define your class A

....

class  B:              

... ..

class C(A, B): # subclass of A and B

....

You can use the issubclass() or isinstance() method to detect.

issubclass() - Boolean function to determine whether a class is a subclass or descendant of another class, syntax: issubclass(sub,sup)

isinstance(obj, Class) Boolean function if obj is an instance object of the Class class or is An instance object of a Class subclass returns true.

Overloading methods

If the function of your parent class method cannot meet your needs, you can overload the method of your parent class in the subclass:

Instance:

#!/usr/bin /python

classParent:​​​​ def myMethod(self) ; The output result of executing the above code is as follows:

Calling child method

Basic overloaded method

The following table lists some common functions that you can override in your own class:

Serial number

Method, description & Simple call

1 __init__ ( self [,args...] )

Constructor

Simple calling method: obj = className(args)

2 __del__( self )

Destructor method, delete an object

Simple calling method: dell obj

3 __repr__( self )

is converted into a form for the interpreter to read

Simple calling method: repr(obj)

4 ​​__str__( self )

is used to convert the value into a form suitable for Human-readable form

Simple calling method: str(obj)

5 __cmp__ (self, x)

Object comparison

Simple calling method: cmp(obj, x)

Operator overloading

Python also supports operator overloading, The example is 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 V ector( self.a + other.a, self.b + other.b)

v1 = Vector(2,10)

v2 = Vector(5,-2)

print v1 + v2

The execution result of the above code is as follows:

Vector(7,8)

Hide data

It is very simple to implement data hiding in python. There is no need to add any keywords in front, as long as Adding two underscores in front of the class variable name or member function can realize the data hiding function. In this way, for the instance of the class, its variable name and member function cannot be used, and for the inherited class of its class, it is also hidden. In this way, its inherited class can define its exact variable name or member function name without causing naming conflicts. Example:

#!/usr/bin/python

class JustCounter:

__secretCount = 0

def count(self):

self.__secretCount += 1

print self.__secretCount

counter = JustCounter()

counter.count()

counter.count()

print counter.__secretCount

Python changes the name to include the class name:

1

2

Traceback (most recent call last):

File "test.py", line 12, in

print counter.__secretCount

AttributeError: JustCounter instance has no attribute '__secretCount'

Python does not allow instantiated classes to access hidden data, but you can use object._className__attrName to access attributes. Replace the last line of code above with the following code:

............ .............

print counter._JustCounter__secretCount

Execute the above code, the execution results are as follows:

1

2

2


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template