Table of Contents
Classes and Examples
Data encapsulation
Home Backend Development Python Tutorial Python object-oriented classes and examples

Python object-oriented classes and examples

Apr 14, 2018 am 10:16 AM
python Example

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
Copy after login

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)
Copy after login
<__main__.Student object at 0x000001A9412A47B8>
<class &#39;__main__.Student&#39;>
Copy after login

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(&#39;%s:%s&#39;%(self.name,self.score))

bart = Student(&#39;Boyuan Zhou&#39;,100)
lisa = Student(&#39;Maomao&#39;,100)
bart.name= &#39;jeff&#39;
print(bart.name)
Copy after login
jeff
Copy after login

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
Copy after login

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(&#39;%s:%s&#39;%(self.name,self.score))

bart = Student(&#39;Boyuan Zhou&#39;,100)
lisa = Student(&#39;Maomao&#39;,100)
bart.name= &#39;jeff&#39;
print(bart.name)
print(bart.score)
Copy after login
jeff
100
Copy after login

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 = {&#39;name&#39;:&#39;jeff&#39;,&#39;score&#39;:100}
>>> std2 = {&#39;name&#39;:&#39;xin&#39;,&#39;score&#39;:0}
>>> def print_score(std):
...     print(&#39;%s:%s&#39;%(std[&#39;name&#39;],std[&#39;score&#39;]))
...
>>> print_score(std1)
jeff:100
>>> print_score(std2)
xin:0
Copy after login

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(&#39;%s:%s&#39;%(self.name,self.score))
Copy after login

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
Copy after login

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(&#39;%s:%s&#39;%(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())
Copy after login
jeff:100
A
Copy after login

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!

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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

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.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

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.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

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.

See all articles