Defining classes and creating instances
In Python, classes are defined by the class keyword. For example, define a person class as follows:
class Person (object): Pass
According to Python 's programming habits, the class name begins with a capital letter, followed by (object), indicating which class the class inherits from. The inheritance of classes is explained in a later section, and now we simply inherit from the object class.
With the definition of the person class, you can create concrete instances such as xiaoming, Xiaohong , and so on. Creating an instance is created using the class name + (), like a function call:
Xiaoming = person () Xiaohong = person ()
Task
Practice defining the person class, creating two instances, printing the instance, and comparing two instances for equality.
Create Instance Properties
Although you can create instances of xiaoming, Xiaohong , and so on through the person class, these instances are not as different as they seem to be in different addresses. In the real world, distinguish xiaoming, Xiaohong to rely on their respective names, gender, birthdays and other attributes.
How do I get each instance to have its own different properties? Since Python is a dynamic language, for each instance, you can assign values directly to their properties, for example, by adding the name, gender , and birth attributes to the instance of xiaoming :
Xiaoming = person () Xiaoming.name = ' Xiao Ming ' xiaoming.gender = ' Male ' Xiaoming.birth = ' 1990-1-1 '
The attributes added to Xiaohong are not necessarily the same as xiaoming :
Xiaohong = person () Xiaohong.name = ' Xiao Hong ' Xiaohong.school = ' No. 1 high school ' Xiaohong.grade = 2
The properties of an instance can be manipulated like normal variables:
Xiaohong.grade = Xiaohong.grade + 1
Task
Create a listof instances of two person classes, assign a value to the name of two instances, and then sort by name .
Python Advanced (iii) object-oriented Programming basics