When to use classes in python
All data in Python are objects. It provides many advanced built-in data types, which are powerful and easy to use. This is one of the advantages of Python. So when to use custom classes? For example, when designing a Person class, if you do not use a custom class, you can do this:
person=['mike', 23, 'male'] #0-姓名, 1-年纪, 2-性别 print(person[0], person[1], person[2])
As you can see, when using the built-in type list, you need to use subscripts to reference member data, which is not intuitive. You can use the dic type instead:
person1={'name':'mike', 'age': 23, 'sex': 'male'} person2={'name':'hellen', 'age': 20, 'sex': 'female'} print(person1['name'], person1['age'], person1['sex'])
This way you don’t have to remember the subscripts and it’s much more intuitive. But the syntax of the dictionary is still a bit cumbersome, and it would be better if it could be referenced like this: person.name, person.age, etc. This is the benefit of the existence of custom classes:
class Person: def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex def __str__(self): #重载该函数便于测试 sep = ',' return self.name+sep+str(self.age)+sep+self.sex person1 = Person('mike', 23, 'male') person2 = Person('hellen', 20, 'female') print(person1) print(person2.name, person2.age, person2.sex)
As you can see, as long as the constructor of this class is defined, instances of this class can be easily generated, and it is also convenient to reference data members, such as It is much more convenient to use built-in types directly. In fact, Python uses the built-in type dic to implement the storage and reference of members of custom classes. From this perspective, custom classes are a simplified way of using built-in classes, and built-in types are necessary internal components of custom types. part. At the same time, because custom classes can define their own member functions or overload predefined methods, custom classes extend the functions of built-in classes and can provide better simulations of real things. This is the advantage of object-oriented programming. . When programming, first form a concept of the thing to be simulated, and then try to use classes to capture the concept. This is the key to object-oriented design. If you need to generate multiple objects of the same type, you should design a custom class to abstract them as much as possible.
Don’t overdo the use of custom classes. Some functions only need to be defined by a function. At this time, there is no need to design a custom class.
The above is the detailed content of When to use classes in python. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

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

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

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

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

The article discusses the role of virtual environments in Python, focusing on managing project dependencies and avoiding conflicts. It details their creation, activation, and benefits in improving project management and reducing dependency issues.
