When to use python class

Reprinted from the product is slightly Library   http://www.pinlue.com/article/2020/04/0515/1810108586721.html

All data in Python is an object, it offers many advanced built-in data types, powerful, easy to use, is one of the advantages of Python. So when working with custom classes do? For example, the design of a Person class, if you do not use a custom class, you can do this:

1

2

person = [ 'mike', 23, 'male'] # 0- name, age, 1-, 2- sex

print(person[0], person[1], person[2])

Can be seen, the use of built-in types List, need subscripts refer to member data, not intuitive. Dic type can use to do:

1

2

3

person1={'name':'mike', 'age': 23, 'sex': 'male'}

person2={'name':'hellen', 'age': 20, 'sex': 'female'}

print(person1['name'], person1['age'], person1['sex'])

So do not remember subscript, more intuitive. But the dictionary syntax is still some trouble, if we can quote like this: person.name, person.age, etc., the better. This is the advantage of a custom class existence:

1

2

3

4

5

6

7

8

9

10

11

12

class Person:

def __init__(self, name, age, sex):

self.name = name

self.age = age

self.sex = sex

def __str __ (self): # override this function and ease of testing

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)

It can be seen that as long as the definition of a good class constructor, it can easily generate an instance of the class, and the reference data members is also very convenient, more convenient than using a built-in type. In fact, Python is to use the built-in types dic to achieve self-storage and quoted a member of the class definition, from this point of view, the custom class is to simplify the use of built-in classes, custom built-in type is a necessary component type inside section. At the same time, due to the custom class can define your own member function or method overloading predefined, so the custom class extends the functionality of the built-in classes, may provide a better simulation of the real thing, this is the advantage of the object-oriented programming . Programming, the first thing to be simulated the formation of the concept, and then try to use the class to seize the concept, which is the key object-oriented design. If you need to generate a plurality of similar objects, you should design a custom class as much as possible to abstract them.

Use custom classes do not too much, just some features need to define a function that can be done, and this time there is no need to design a custom class.

 

 

Published 60 original articles · won praise 58 · Views 140,000 +

Guess you like

Origin blog.csdn.net/yihuliunian/article/details/105365851