Python Practical Notes (26) object-oriented advanced programming--Custom classes

Source: Internet
Author: User

Python's class allows you to define many custom methods that make it very easy to generate specific classes. The following are the common custom methods of centralization:

How can you print it well? Just define a good __str__() method and return a nice-looking string:

__str__()

>>> class Student(object):... def __init__(self, name):... self.name = name... def __str__(self):... return ‘Student object (name: %s)‘ % self.name...>>> print(Student(‘Michael‘))Student object (name: Michael)

This kind of printed example, not only good-looking, but also easy to see the important data inside the instance.

But careful friends will find that the direct knocking variable print is not used, the printed example is not good to see:

>>> s = Student(‘Michael‘)>>> s<__main__.Student object at 0x109afb310>

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:

class Student(object):    def __init__(self, name): self.name = name def __str__(self): return ‘Student object (name=%s)‘ % self.name __repr__ = __str__

Python Practical Notes (26) object-oriented advanced programming--Custom classes

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.