Call of magic methods for python Learning

Source: Internet
Author: User

Call of magic methods for python Learning

In python, there are some functions with two underscores (_) on the front and back. Such functions are called in special circumstances, rather than by their names. The following describes several important functions in detail.

The _ init _ function is called automatically when a specific object is created.

class People:def __init__(self):self.university="shandong"def getUniversity(self):return self.universityxiang=People() #when you create an object, the __init__ method will be excuted dynamicallyprint xiang.getUniversity() class student(People):def __init__(self):People.__init__(self)name="xiang"gao=student()print gao.getUniversity()

When xiang = People () is run in the above function, the _ init _ () function is automatically called, when subclass inherits the _ init _ function of the parent class, it uses Father. in _ init _ (self), self indicates the subclass itself.

class counterList(list):def __init__(self,*args):self.counter=0list.__init__(self,*args)def __getitem__(self,index): #it will be exceted dynamically when you use []self.counter+=1print "I am running"return list.__getitem__(self,index)count=counterList(range(0,10))print count.counterprint count[0]+count[1]
The getitem () function is automatically called when [] is used.

Use of iterator functions:

class Fibs:def __init__(self):self.a=0self.b=1def next(self):self.a,self.b=self.b,self.a+self.breturn self.adef __iter__(self):return selffibs=Fibs()for f in fibs:if f>5:print f break
The next and _ iter _ functions must be implemented using the built-in iterator.

In addition, there are static functions and variable functions that can be called directly using class names in python.

class MyClass:@staticmethod  #create static methoddef smath():print "this is static method"@classmethod#create class methoddef cmath(clf):print "this is class method"MyClass.smath()MyClass.cmath()






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.