search
HomeBackend DevelopmentPython TutorialAn example tutorial to create a simple class

Create a simple class

Each real column created based on the Dog class will store the name and age. We gave each puppy the ability to squat (sit()) and roll (roll_over()):

 1 class Dog(): 2     """一次模拟小狗的简单尝试""" 3     def __init__(self, name, age): 4         """初始化属性name和age""" 5         self.name = name 6         self.age = age 7     def sit(self): 8         """模拟小狗被命令时蹲下""" 9         print(self.name.title() + "now is sitting.")10     def roll_over(self):11         """模拟小狗被命令时打滚"""12         print(self.name.title() + "rolled over!")13 my_dog = Dog('tom','3')14 print("my dog name is " + my_dog.name.title() )
By convention, in Python, the first letter is capitalized The name refers to the class: functions in the class are called methods
method__init__(), with 2 underscores at the beginning and end, this is a convention to avoid Python default methods A name conflict occurred with a normal method. We define the method __init__() to contain three formal parameters: self, name and age. In the definition of this method, the parameterself is essential and must be located in front of other formal parameters. Why must the formal parameter self be included in the method definition? Because when Python calls this __init__() method to create a Dog instance, the actual parameter self will be automatically passed in. Both variables self_name and self_age are prefixed with self. Variables prefixed with self are available to all methods in the class. We can also access these variables through any instance column of the class. Variables like this that are accessible through an instance are called properties.
#In python2.X, if you create a class, you need to add (object) after the brackets.
Accessing properties

Continuing with the above example, the method __init__() creates an instance representing a specific puppy and sets it with the value we provide The attributes name and age, and the method __init__() do not explicitly contain a return statement, but python automatically returns an example representing this puppy. We store this example in the variable my_dog.
class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性name和age"""self.name = name
        self.age = agedef sit(self):"""模拟小狗被命令时蹲下"""print(self.name.title() + " now is sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + " rolled over!")
my_dog = Dog('tom',3)print(my_dog.name)print(my_dog.age)#运行结果tom3

Call method

class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性name和age"""self.name = name
        self.age = agedef sit(self):"""模拟小狗被命令时蹲下"""print(self.name.title() + " now is sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + " rolled over!")
my_dog = Dog('tom',3)
my_dog.sit()
my_dog.roll_over()#运行结果Tom now is sitting.
Tom rolled over!
After creating an instance based on the Dog class, You can use period notation to call any method defined by Dog

Create multiple instances

class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):"""初始化属性name和age"""self.name = name
        self.age = agedef sit(self):"""模拟小狗被命令时蹲下"""print(self.name.title() + " now is sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + " rolled over!")
my_dog = Dog('tom',3)
your_dog = Dog('Mei',2)print("My dog name is " + my_dog.name.title())print("Your dog name is " + your_dog.name.title())#运行结果My dog name is Tom
Your dog name is Mei
You can press Create any number of instances based on the class on demand.

Using classes and instances

Specify default values ​​for properties

Each property in a class must have an initial value , even if the value is 0 or an empty string, in some cases, such as when setting a default value, it is okay to specify this initial value in the method __init__(). If you do this for an attribute, there is no need to Contains formal parameters that provide initialization for it.
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_name
my_car = Car('audi', 'a4', '2017')print(my_car.model)print(my_car.get_descri_name())#运行结果a42017 a4 audi

Directly modify the value of the attribute

class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_name
my_car = Car('audi', 'a4', '2017')print(my_car.get_descri_name())
my_car.year = 2016print(my_car.get_descri_name())#运行结果2017 a4 audi2016 a4 audi

Modify by method

class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading:
            self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")
my_car = Car('audi', 'a4', '2017')
my_car.read_odometer()
my_car.odometer_reading = 10    #直接修改里程值my_car.update(200)     #通过方法修改里程my_car.read_odometer()
my_car.increment_odometer(10)
my_car.read_odometer()#运行结果This car has 100 miles on it.
This car has 200 miles on it.
This car has 210 miles on it.

Inheritance

If we want another class to inherit the attributes of another class, we can add the class in brackets after the class Name, for example:

class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading:
            self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")class ElectricCar(Car):"""电动汽车的独特特性"""def __init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', '2016')print(my_tesla.get_descri_name())#运行结果2016 model s tesla
In order to inherit the attributes of the parent class,

also needs to add a special function super() to help Python associate the parent class with the subclass.

In python2.X, the format of class supper is as follows:
supper(Eletric,self).__init__(make, model, year)
Give sub Class definition attributes and methods
After a class inherits another class, you can add new attributes and methods that distinguish the subclass and the parent class.
Use instances as attributes
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading:
            self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")class Battery():"""一次模拟电动汽车"""def __init__(self,battery_size=70):"""初始化电瓶的属性"""self.battery_size = battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a " + str(self.battery_size) + "-kwh battery.")class ElectricCar(Car):"""电动汽车的独特特性"""def __init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year)
        self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', '2016')print(my_tesla.get_descri_name())
my_tesla.battery.describe_battery()#运行结果2016 model s tesla
This car has a 70-kwh battery.

Import class

Import single or multiple classes
A file car.py
class Car():"""一次模拟汽车的简单尝试"""def __init__(self, make, model, year):"""汽车的初始化"""self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 100def get_descri_name(self):"""描述汽车"""long_name = str(self.year) + ' ' + self.model + ' ' + self.makereturn long_namedef update(self, mile):"""更新里程值"""if mile > self.odometer_reading:
            self.odometer_reading = mileelse:print("You can't roll back an odometer")def increment_odometer(self,mile):"""增加里程"""self.odometer_reading += miledef read_odometer(self):"""打印汽车的里程"""print("This car has " + str(self.odometer_reading) + " miles on it.")class Battery():"""一次模拟电动汽车"""def __init__(self,battery_size=70):"""初始化电瓶的属性"""self.battery_size = battery_sizedef describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a " + str(self.battery_size) + "-kwh battery.")class ElectricCar(Car):"""电动汽车的独特特性"""def __init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year)
        self.battery = Battery()
Create another file my_car.py and import a class

from  car import Car
my_car = Car('audi', 'a4', '2017')
Multiple classes can be stored in a module, so multiple classes can be imported at one time

from car import Car,Battery,ElectricCar
my_tesla = ElectricCar('tesla', 'model s', '2016')print(my_tesla.get_descri_name())
my_tesla.battery.describe_battery()

Import the entire module

import car     #导入整个模块的时候,需要使用句点表示法访问需要的类
my_tesla = car.ElectricCar('tesla', 'model s', '2016')print(my_tesla.battery)

Import all classes

from car import *    #导入所有的类

 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

The above is the detailed content of An example tutorial to create a simple class. For more information, please follow other related articles on the PHP Chinese website!

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
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version