Python3 Learning Notes Custom class

Source: Internet
Author: User

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

#作用: Internal information can be printed directly
Print (Student ('Michael')) Student object (Name:michael)

__getattr__

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:

classStudent (object):def __init__(self): Self.name='Michael'    def __getattr__(self, attr):ifattr=='score':            return99

>>> s =Student ()
>>> S.name
'Michael'
>>> S.score
about
#返回函数也是完全可以的:
Class Student (object): def__getattr__(self, attr): if attr=='age': returnLambda: 25
Just call the method to change to:
>>> S.age ()
25

Any call s.abc will be returned None , because the default return that we define is __getattr__ None . To allow class to respond to only a few specific properties, we are going to throw the error according to the Convention AttributeError :

class Student (object):     def __getattr__ (self, attr):         if attr=='age':            returnLambda: 25        raise attributeerror ('\ ' student\ ' object has no attribute \ '%s\ ' % attr

This actually allows all the properties and method invocations of a class to be dynamically processed, without any special means.

Action Example:

With completely dynamic __getattr__ , we can write a chain call:

classChain (object):def __init__(Self, path="'): Self._path=Pathdef __getattr__(self, path):returnChain ('%s/%s'%(Self._path, path))def __str__(self):returnSelf._path__repr__=__str__




>>> Chain (). Status.user.timeline. List
'/status/user/timeline/list '
In this way, regardless of the API changes, the SDK can be based on the URL to achieve a full dynamic call, and not with the increase of the API to change!

__call__

In any class, you can simply __call__() invoke the instance by defining a method.

class Student (object):     def __init__ (self, name):         = name    def__call__(self):        print('My Name is%s. ' % self.name)


The method is called as follows:
>>> s = Student (' Michael ')
# Self parameter do not pass in
Is Michael.

Python3 Learning Notes Custom class

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.