Python 0 Basic Primer for the Magic method in class 13

Source: Internet
Author: User
The previous blog simply said the basic knowledge of the class, the following emphasis on some of the methods commonly used in the class. An obvious sign of the so-called magic method is that the method name is contained by the _ two underscore.
(1) _init_
If you do not overload or override this method, the system will automatically invoke the default Init method, and if you override the method to satisfy your needs, the method you override will automatically override the system's default method.

Class ball:     def __init__ (self,name):          self.name=name     def Kick (self):          print ("My name is%s, damn it, who kicked me ...") Self.name) a=ball ("Potato") a.kick ()

After rewriting the Init method itself, we can fill in a parameter when instantiating an object.

Class Rectangle:     def __init__ (self,x,y):          self.x=x          self.y=y     def getperi (self):          return (self.x+ SELF.Y)     * * def getarea (self):          return self.x * self.yrect=rectangle (3,4) print (Rect.getarea ()) Print ( Rect.getperi ())

(2) New (two underline before and after)
This method is called before the Init method and is not normally used, so there is no redundancy here.
(3) Del (with two underscores before and after)
Role: Deleting objects

Class C:     def __init__ (self):          print ("I am the __init__ method, I am called")     def __del__ (self):          print ("I am the __del__ method, I was called ") c1=c () C2=c1c3=c2del C3del C2del C1

It is important to note that the garbage collection mechanism is only called when all the tags that point to C1 are deleted
Here are a few common magical methods that will be added later on.

The above is the content of the Magic method in the basic primer 13 of Python 0, for more information please follow topic.alibabacloud.com (www.php.cn)!

  • 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.