Liaoche Python excerpt 7

Source: Internet
Author: User

1. What if we want to restrict the properties of an instance? For example, only add and attributes to student instances are allowed name age .

For the purpose of limiting, Python allows you to define a special variable when defining a class __slots__ to limit the attributes that the class instance can add:

2, use __slots__ to note that the __slots__ defined properties only work for the current class instance, and it does not work for inherited subclasses.

3, in order to limit the scope of score, you can use a set_score() method to set the score, and then through a get_score() to get results, so that in the set_score() method, you can check the parameters

4. Because Python allows multiple inheritance, mixin is a common design.

Only single-inherited languages, such as Java, are allowed to use the mixin design.

5.

This is because the direct display of variable calls is not __str__() , but the __repr__() difference between the two is to return the string that the __str__() user sees, and the __repr__() string that the program developer sees, that __repr__() is, for debugging services.

The solution is to define one more __repr__() . But it's usually __str__() __repr__() the same as the code, so there's a lazy way to do it:

1>>>classStudent (object):2     def __init__(self,name):3Self.name =name4     def __str__(self):5         return"Student Object (name:%s)"%Self.name6     __repr__=__str__7 8     9>>> S=student ('Mike')Ten>>>s OneStudent Object (name:mike)

Liaoche Python excerpt 7

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.