Create instance properties in Python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.