Python some custom methods (functions)

Source: Internet
Author: User

__str__() __call__() __repr__()Method
>>> class Student (object):    def __init__ (self, name):        self.name = name    def __call__ (self):        Print (' My name is%s. '% self.name)    def-__str__ (self): return ' I am a print call for name:%s! ' %self.name    def __repr__ (self): return ' I am a print var value for name:%s! ' %self.name>>> s = Student (' Lucy ') >>> s     //call __repr__ () I am a print var value for Name:lucy!>&G t;> s ()   //Call __call__ () My name was lucy.>>> print S    //call __str__ () I am a print call for Name:lucy !

  



 __str__是调用print 打印,
__repr__是直接写变量时打印的

__iter__ ()方法

如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法
__getitem__()Method

To act as a list to take out elements according to subscript, you need to implement the __getitem__() method

__getattr__()Method

That is to write a __getattr__() method that dynamically returns a property

class Student(object):    def __init__(self): self.name = ‘Michael‘ def __getattr__(self, attr): if attr==‘score‘: return 99
  raise
AttributeError(‘\‘Student\‘ object has no attribute \‘%s\‘‘ % attr) //调用不存在的属性是,抛出
>>> s = Student()>>> s.name‘Michael‘>>> s.score99

This section describes some of the most commonly used customization methods, as well as a number of customizable methods, please refer to the official Python documentation.
Http://docs.python.org/2/reference/datamodel.html#special-method-names













Python some custom methods (functions)

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.