search

Python object-oriented

Nov 23, 2016 pm 02:09 PM
python

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

b = a # Increase the count of

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

del a       # Decrease the count of reference

b = 100 # Decrease the count of reference

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

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

<p></p><p>The above example running results are as follows:</p><p></p><pre class="brush:php;toolbar:false"><p>3083401324 308 3401324 3083401324</p><p>Point destroyed</p><p> </p><p></p><p>Note: Usually you need to define a class in a separate file, </p><p>Inheritance of class</p><p>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. </p><p>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. </p><p>Some features of inheritance in python: </p><p>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. </p><p>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</p><p>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). </p><p>If more than one class is listed in the inheritance tuple, then it is called "multiple inheritance". </p><p>Syntax: </p><p>Declaration of derived classes, similar to their parent classes, with a list of inherited base classes following the class name, as follows: </p><p></p><p></p><p>class SubClassName (ParentClass1[, ParentClass2, ... :       # define parent class</p><p>    parentAttr = 100e DEF __init __ (Self): </p><p> Print "Calling Parent Constructor" </p><p> Def ParentMethod (Self): </p><p> Print 'Callling Parent Method'</p><p> </p><p> DEF SELF, Attr): </p><p> Parent.parentAttr = attr</p><p></p><p> def getAttr(self):</p><p> print "Parent attribute:", Parent.parentAttr</p><p></p><p>classChild(Parent): #def __init__(self):</p><p> print "Calling child constructor"</p><p> def childMethod(self):</p><p> print 'Calling child method'</p><p> </p><p>c =Child()             # Instantiate the subclass </p><p>c.childMethod()       # Call the method of the subclass </p><p>c.parentMethod()         # Call the method of the parent class </p><p>c.setAttr(200)                          Tc.getattr ()# The method of calling the parent class again </p><p></p><p> </p><p></p><p> The above code execution results are as follows: </p><p></p><p></p><p>Calling Child Constructor</p><p>Calling Child Method</p><p>Calling Parent ATTRIBUTE: 200 </p><p> </p><p></p><p>You can inherit multiple classes </p><p></p><p></p><p>class A:         # define your class A</p><p>....</p><p> </p><p>class  B:              </p><p>... ..</p><p> </p><p>class C(A, B): # subclass of A and B</p><p>....</p><p> </p><p></p><p> You can use the issubclass() or isinstance() method to detect. </p><p>issubclass() - Boolean function to determine whether a class is a subclass or descendant of another class, syntax: issubclass(sub,sup)</p><p>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. </p><p>Overloading methods</p><p>If the function of your parent class method cannot meet your needs, you can overload the method of your parent class in the subclass: </p><p>Instance: </p><p></p><p></p><p>#!/usr/bin /python</p><p></p><p>classParent:​​​​ def myMethod(self) ; The output result of executing the above code is as follows: </p> <p></p><p></p><p>Calling child method</p><p> </p><p></p><p>Basic overloaded method</p><p>The following table lists some common functions that you can override in your own class: </p><p></p><p>Serial number</p><p>Method, description & Simple call</p><p></p><p>1 __init__ ( self [,args...] )</p>Constructor<p>Simple calling method: obj = className(args) </p><p>2 __del__( self )</p>Destructor method, delete an object<p> Simple calling method: dell obj </p><p>3 __repr__( self )</p> is converted into a form for the interpreter to read <p> Simple calling method: repr(obj) </p><p>4 ​​__str__( self )</p> is used to convert the value into a form suitable for Human-readable form<p>Simple calling method: str(obj) </p><p>5 __cmp__ (self, x)</p>Object comparison<p>Simple calling method: cmp(obj, x) </p><p>Operator overloading</p><p>Python also supports operator overloading, The example is as follows: </p><p></p><p></p><p>#!/usr/bin/python</p><p><br><br>class Vector:</p><p> def __init__(self, a, b):<br><br> self.a = a</p><p> self.b = b <br><br></p><p> def __str__(self):<br><br> return 'Vector (%d, %d)' % (self.a, self.b) </p><p> <br><br> def __add__(self,other):</p><p> return V ector( self.a + other.a, self.b + other.b)</p><p> </p><p>v1 = Vector(2,10)</p><p>v2 = Vector(5,-2)</p><p>print v1 + v2</p><p> </p><p></p> <p>The execution result of the above code is as follows: </p><p></p><p></p><p>Vector(7,8)</p><p> </p><p></p><p>Hide data</p><p>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: </p><p></p><p></p><p>#!/usr/bin/python</p><p> </p><p>class JustCounter:</p><p> __secretCount = 0</p><p> </p><p> def count(self):</p><p> self.__secretCount += 1</p><p> print self.__secretCount</p><p></p><p>counter = JustCounter()</p><p>counter.count()</p><p>counter.count()</p><p>print counter.__secretCount</p><p> </p><p></p><p>Python changes the name to include the class name:</p><p></p><p></p><p>1</p><p>2 </p> <p>Traceback (most recent call last):</p><p> File "test.py", line 12, in <module></module></p><p> print counter.__secretCount</p><p>AttributeError: JustCounter instance has no attribute '__secretCount'</p><p> </p><p></p> <p> 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: </p><p></p><p></p><p>............ .............</p><p>print counter._JustCounter__secretCount</p><p> </p><p></p><p>Execute the above code, the execution results are as follows: </p><p></p><p>1</p><p>2</p><p>2</p><p><br></p>
Statement
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
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.