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 .
class Person (object):
Pass
P1 = person ()
P1.name = ' Bart '
P2 = person ()
P2.name = ' Adam '
P3 = person ()
P3.name = ' Lisa '
L1 = [P1, p2, p3]
L2 = sorted (L1,key=lambda x:x.name)
Print L2[0].name
Print L2[1].name
Print L2[2].name
Create instance properties in Python