Python: Custom-made classes

Source: Internet
Author: User

__str__

__repr__

__iter__

__next__

__getitem__

__getattr__

Normally, when we call a method or property of a class, it will be an error if it does not exist. For example Student , define a class:

class Student (object):     def __init__ (self):         ' Michael '

Call name Properties, no problem, but call a nonexistent score property, there is a problem:

>>> s = Student ()print(s.name) Michaelprint(s.score) Traceback ( Most recent call last):  'Student'score '

The error message clearly tells us that the attribute was not found score .

To avoid this error, in addition to adding a score property, Python has another mechanism, which is to write a __getattr__() method that dynamically returns an attribute. Modify the following:

 class   Student (object):  def  __init__   =  " michael  "  def  __getattr__  " Span style= "COLOR: #000000" > (self, attr):  if  attr=="  score   " :  return " 

When a non-existent property is called, for example score , the Python interpreter attempts to invoke __getattr__(self, ‘score‘) the property, so that we have a chance to return score the value:

>>> s = Student ()>>> s.name'Michael'>>> S.score99

The return function is also perfectly possible:

class Student (object):     def __getattr__ (self, attr):         if attr=='age':            returnLambda: 25

Just call the method to change to:

>>> s.age ()25

Note that an existing attribute is called only if no attribute is found, __getattr__ for example name , it is not located in __getattr__ .

Python: Custom-made classes

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.