The content shared with you in this article is about Python object-oriented classes and examples, which has certain reference value. Friends in need can refer to
Classes and Examples
The most important concepts of object-oriented are classes and instances. It must be remembered that classes are abstract templates, such as the Student class, while instances are specific " Object", each object has the same methods, but their data may be different.
Still taking the Student class as an example, in Python, defining a class is through the class keyword:
class Student(object): pass
class is followed by the class name, which is Student. The class name usually starts with a capital. The word followed by (object) indicates which class the class is inherited from. We will talk about the concept of inheritance later. Usually, if there is no suitable inheritance class, the object class is used. This is what all classes will eventually do. Inherited classes.
After defining the Student class, you can create an instance of Student based on the Student class. Creating an instance is achieved through the class name ():
class Student(object): pass bart = Student() print(bart) print(Student)
<__main__.Student object at 0x000001A9412A47B8> <class '__main__.Student'>
As you can see, the variable bart points to An instance of Student, the following 0x000001A9412A47B8 is the memory address, the address of each object is different, and Student itself is a class.
You can freely bind attributes to an instance variable. For example, bind a name attribute to the instance bart:
class Student(object): def __init__(self,name,score): self.name = name self.score = score def print_score(self): print('%s:%s'%(self.name,self.score)) bart = Student('Boyuan Zhou',100) lisa = Student('Maomao',100) bart.name= 'jeff' print(bart.name)
jeff
Because classes can serve as templates Therefore, when creating an instance, we can force-fill in some attributes that we think must be bound. By defining a special __init__ method, when creating an instance, the name, score and other attributes are tied to it:
class Student(object): def __init__(self,name,score): self.name = name self.score = score
Note that the first parameter of the __init__ method is always self, which means The created instance itself, therefore, within the __init__ method, you can bind various properties to self, because self points to the created instance itself.
With the __init__ method, when creating an instance, you cannot pass in empty parameters. You must pass in parameters that match the __init__ method, but self does not need to be passed. The Python interpreter itself The instance variable will be passed in:
class Student(object): def __init__(self,name,score): self.name = name self.score = score def print_score(self): print('%s:%s'%(self.name,self.score)) bart = Student('Boyuan Zhou',100) lisa = Student('Maomao',100) bart.name= 'jeff' print(bart.name) print(bart.score)
jeff 100
Compared with ordinary functions, the function defined in the class has only one difference, that is, the first parameter is always the instance variable self, and when calling, there is no need to pass the parameter. Other than that, class methods are no different from ordinary functions, so you can still use default parameters, variable parameters, keyword parameters, and named keyword parameters.
Data encapsulation
An important feature of object-oriented programming is data encapsulation. In the Student class above, each instance has its own name and score data. We can access this data through functions, such as printing a student's score
>>> std1 = {'name':'jeff','score':100} >>> std2 = {'name':'xin','score':0} >>> def print_score(std): ... print('%s:%s'%(std['name'],std['score'])) ... >>> print_score(std1) jeff:100 >>> print_score(std2) xin:0
However, since the Student instance itself owns this data, to access this data, there is no need to access it from external functions. You can directly Define the function to access data inside the Student class, thus encapsulating the "data". These functions that encapsulate data are associated with the Student class itself. We call them methods of the class:
class Student(object): def __init__(self,name,score): self.name = name self.score = score def print_score(self): print('%s:%s'%(self.name,self.score))
To define a method, except that the first parameter is self, the others are the same as ordinary functions. To call a method, you only need to call it directly on the instance variable. Except for self, you do not need to pass it. Other parameters are passed in normally:
bart.print_score() jeff:100
In this way, when we look at the Student class from the outside, we only need to know how to create an instance. The name and score need to be given, and how to print is defined internally by the Student class. These data and logic are "encapsulated" and are easy to call, but there is no need to know the details of the internal implementation.
Another benefit of encapsulation is that you can add new methods to the Student class, such as get_grade:
class Student(object): def __init__(self,name,score): self.name = name self.score = score def print_score(self): print('%s:%s'%(self.name,self.score)) def get_grade(self): if self.score >=90: return 'A' elif self.score>=600: return 'B' else: return 'C' bart = Student('Boyuan Zhou',100) lisa = Student('Maomao',100) bart.name= 'jeff' bart.print_score() print(bart.get_grade())
jeff:100 A
Related recommendations:
About python object-oriented sample code
The above is the detailed content of Python object-oriented classes and examples. For more information, please follow other related articles on the PHP Chinese website!

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
