Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the magic method in python object-oriented programming?

Shulou Source: shulou.com Published: 2022-06-01 18:24:16 10月16日 Update

Python object-oriented programming what is the magic method, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Learn the object-oriented programming-magic method of python today.

Create a new python file named py3_oop5.py, and write the operation code in this file:

# object-oriented programming # Magic method

# print the value of print (1 / 2) # "here is actually calling the magic method of # int _ _ add__ () print (int.__add__ (1 ~ 2)) # print string concatenation print ('aura') # # here is actually calling the magic method of # str _ _ add__ () print (str.__add__ ('a') ('b')) # continue to look at the Employee class class Employee: raise_amount = 1.0 defines the column variable def _ _ init__ (self,first,last,pay): self.first = first self.last = last self.email = first +'.'+ last +'@ email.com' self.pay = pay

Def fullname (self): return'{} '.format (self.first,self.last)

Def apply_raise (self): self.pay = int (self.pay * self.raise_amount) # the following magic method is # actually rewrite the built-in functions repr () and str () # learn later # repr is generally used for debugging Logging uses # for developers def _ _ repr__ (self): return 'Employee {}' .format (self.first,self.last,self.pay) # str is generally used to display information # for end users def _ _ str__ (self): return'{}-{} '.format (self.fullname () Self.email) # rewrite _ _ add__ # calculate salary plus def _ _ add__ (self,other): return self.pay + other.pay # rewrite _ _ len__ # calculate full name length def _ _ len__ (self): return len (self.fullname ())

Emp_1 = Employee emp_2 = Employee ('Mc','User',60000) # print object, call # _ str__ () print (emp_1.__str__ ()) # T Bag-T.Bag@email.comprint (emp_1.__repr__ ()) # Employee T Bag 50000print (emp_1 + emp_2) # 110000print (len (emp_2)) # 7 by default

Running result:

33ababT Bag-T.Bag@email.comEmployee T Bag 500001100007 is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Tags: Methods magic objects programming reality files learning help clarity code information full name content functions variables characters strings for this salary developer Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information MySQL vpn Microsoft Apple