current position:Home>Python object oriented programming 01: introduction classes and objects
Python object oriented programming 01: introduction classes and objects
2022-01-31 16:03:47 【Lei Xuewei】
「 This is my participation 11 The fourth of the yuegengwen challenge 13 God , Check out the activity details :2021 One last more challenge 」
ceremonial Python Column No 36 piece , Classmate, stop , Don't miss this from 0 The beginning of the article !
Previously, I wrote other functions such as file reading and file processing , It uses os library .
I wanted to share os library , Finding this library may be difficult for beginners , So we'll talk later at the right time , Because a lot of file system operations are designed , More biased Linux Operation and maintenance .
Let's look at face object programming first , That's what many people talk about OOP(Object-oriented Programming)
What is object oriented programming ?
Have we heard of process oriented , It's better to compare them together .
Simply understand , Process oriented is to solve all files with functions , Simple and crude !
Object oriented is Process oriented programming And then there was , Without object-oriented programming, many programs are not developed as usual .
object-oriented , Also use the function , But there is an extra net , This net puts one or more functions , Associated with data , Then it is called a kind of thing , That is, in the program ‘ class ’(class)
Defining classes , Feel it from the specific code !
object-oriented programming , The first concept put forward is ‘class’, class :
# So that's one class The definition code of :
class hello_class():
pass
Copy code
And then through class_name() This is used to call the production object .
Upgrade the code a little , Let's see. :
class hello_class():
pass
# Output class information
print(hello_class)
print(type(hello_class))
# Create instance object of class
print(hello_class())
print(type(hello_class()))
Copy code
Just to add a little bit :
print The function outputs the result of the class object : Usually <'class full name ‘ object at id Serial number >
Here are the results :
Here we add new knowledge points : Class instance object , Usually say directly , example .
The instance is class The object of production , All some hello_class Type of object ( adopt type Function to obtain ) Must be hello_class.
Observation of multiple classes and objects
After reading a class , Let's look at the comparison between the two classes , The results are the same .
The following is the definition of the two classes and the code display of the generated object :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/15 11:58 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
class student(object):
def __init__(self):
print("hello, I am student")
class programmer(object):
def __init__(self):
print("hello, I am programmer")
class student(object):
def __init__(self):
print("hello, I am student")
class programmer(object):
def __init__(self):
print("hello, I am programmer")
s1 = student
print(s1)
p1 = programmer
print(p1)
s11 = student
print(s11)
p11 = programmer
print(p11)
print("*" * 16)
# Create objects
s2 = student()
print(s2)
p2 = programmer()
print(p2)
# Create objects
s3 = student()
print(s3)
p3 = programmer()
print(p3)
Copy code
Explain a little :
s1 and p1 The printout of these two variables is ‘class’ Type of .
s11 and p11 The printout of these two variables is ‘class’ Type of , however s1 Follow s11,p1 Follow p11 It is the same. .
s2 and p2 The printout of these two variables is 'object' Type of .
s3 and p3 The printout of these two variables is 'object' Type of .\
Here are the results :
Come here , Everyone should know class and object What's the difference
class : Describes the fixed relationship between functions and attributes ( Class instance ) object : A living individual based on this fixed relationship , its id It is changing. .
Add the properties of the class ( Data section )
The school committee defined a student class , And created two student objects .
Directly copy and run the following code :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/15 11:58 Afternoon
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Lei Xuewei
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
class student(object):
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def study(self):
print(f"{self.name} : study hard , Day day up !")
s1= student(" The small white ")
print(s1)
print(s1.get_name())
print(s1.study())
s2 = student(" Student fans of the School Committee : Ha ha ha ")
print(s2)
print(s2.get_name())
print(s2.study())
Copy code
We saw their id It's always different ( Run a few times to see ).
Then every student has a name attribute ( Carry name data ), And three function properties ( Respectively used to get the name , Change of name , Study ).
Then we called each student's study function , Output their learning status .
summary
Python Simple design of language , Makes object-oriented programming very simple , It's easy to define and get objects .
The code above is very simple , But you can feel the presentation of classes and objects well , Practice more .
by the way , like Python Friend, , Please pay attention to Python Basic column or Python From getting started to mastering the big column
Continuous learning and continuous development , I'm Lei Xuewei !
Programming is fun , The key is to understand the technology thoroughly .
Welcome to wechat , Like support collection !
copyright notice
author[Lei Xuewei],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201311603465161.html
The sidebar is recommended
- Django (make an epidemic data report)
- Daily python, Part 8 - if statement
- Django model class 1
- The same Python code draws many different cherry trees. Which one do you like?
- Python code reading (Chapter 54): Fibonacci sequence
- Django model class 2
- Python crawler Basics
- Mapping 3D model surface distances using Python VTK
- How to implement encrypted message signature and verification in Python -- HMAC
- leetcode 1945. Sum of Digits of String After Convert(python)
guess what you like
-
leetcode 2062. Count Vowel Substrings of a String(python)
-
Analysis of Matplotlib module of Python visualization
-
Django permission management
-
Python integrated programming -- visual hot search list and new epidemic situation map
-
[Python data collection] scripy realizes picture download
-
Python interface automation test framework (basic part) -- loop statement of process control for & while
-
Daily python, Chapter 9, while loop
-
Van * Python | save the crawled data with docx and PDF
-
Five life saving Python tips
-
Django frequency control
Random recommended
- Python - convert Matplotlib image to numpy Array or PIL Image
- Python and Java crawl personal blog information and export it to excel
- Using class decorators in Python
- Untested Python code is not far from crashing
- Python efficient derivation (8)
- Python requests Library
- leetcode 2047. Number of Valid Words in a Sentence(python)
- leetcode 2027. Minimum Moves to Convert String(python)
- How IOS developers learn Python Programming 5 - data types 2
- leetcode 1971. Find if Path Exists in Graph(python)
- leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores(python)
- Python interface automation test framework (basic) -- basic syntax
- Detailed explanation of Python derivation
- Python reptile lesson 2-9 Chinese monster database. It is found that there is a classification of color (he) desire (Xie) monsters during operation
- A brief note on the method of creating Python virtual environment in Intranet Environment
- [worth collecting] for Python beginners, sort out the common errors of beginners + Python Mini applet! (code attached)
- [Python souvenir book] two people in one room have three meals and four seasons: 'how many years is it only XX years away from a hundred years of good marriage' ~?? Just come in and have a look.
- The unknown side of Python functions
- Python based interface automation test project, complete actual project, with source code sharing
- A python artifact handles automatic chart color matching
- Python crawls the map of Gaode and the weather conditions of each city
- leetcode 1275. Find Winner on a Tic Tac Toe Game(python)
- leetcode 2016. Maximum Difference Between Increasing Elements(python)
- Run through Python date and time processing (Part 2)
- Application of urllib package in Python
- Django API Version (II)
- Python utility module playsound
- Database addition, deletion, modification and query of Python Sqlalchemy basic operation
- Tiobe November programming language ranking: Python surpasses C language to become the first! PHP is about to fall out of the top ten?
- Learn how to use opencv and python to realize face recognition!
- Using OpenCV and python to identify credit card numbers
- Principle of Python Apriori algorithm (11)
- Python AI steals your voice in 5 seconds
- A glance at Python's file processing (Part 1)
- Python cloud cat
- Python crawler actual combat, pyecharts module, python data analysis tells you which goods are popular on free fish~
- Using pandas to implement SQL group_ concat
- How IOS developers learn Python Programming 8 - set type 3
- windows10+apache2. 4 + Django deployment
- Django parser