Magic methods in class 13 of zero-Basic Python beginners

Source: Internet
Author: User
The previous blog briefly introduced the basic knowledge of the class. The following describes some common methods of the class. An obvious sign of the so-called magic method is that the method name is enclosed by _ underscores. The previous blog briefly introduced the basic knowledge of the class. The following describes some common methods of the class. An obvious sign of the so-called magic method is that the method name is enclosed by _ underscores.
(1) _ init _
If you do not need to reload or override this method, the system will automatically call the system's default init method. if you rewrite this method to meet your needs, the method you override will automatically overwrite the default method of the system.

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"). kick ()

After self-rewriting the init method, we can enter 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)*2     def getArea(self):          return self.x * self.yrect=Rectangle(3,4)print(rect.getArea())print(rect.getPeri())

Purpose: delete an object.

Class C: def _ init _ (self): print ("I'm _ init _, I was called") def _ del _ (self): print ("I am _ del _ method, I was called") c1 = C () c2 = c1c3 = c2del c3del c2del c1

Let's talk about several common magic methods first, and then we will continue to add them.

The above is the content of the magic methods in class 13 of the zero-Basic Python beginners. For more information, see PHP Chinese network (www.php1.cn )!

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.