Python object-oriented
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: 2000Name : Manni ,Salary: 5000Total 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 8delattr(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 employeesEmployee.__name__: Employee Employee.__module__: __main__Employee.__bases__: ()Employee.__dict__: {'__module__': '__main__', 'displayCount':
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...] )
ConstructorSimple calling method: obj = className(args)
2 __del__( self )
Destructor method, delete an objectSimple calling method: dell obj
3 __repr__( self )
is converted into a form for the interpreter to readSimple calling method: repr(obj)
4 __str__( self )
is used to convert the value into a form suitable for Human-readable formSimple calling method: str(obj)
5 __cmp__ (self, x)
Object comparisonSimple 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 = aself.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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
