首页 > 解决方案 > 我无法理解以下代码中发生了什么...#Method Overloading

问题描述

class something:

    def __init__(self, pages):
        self.noofpages=pages

    def __add__(self,b):
        return str(self.noofpages + b.noofpages)+'hii'

m=something(10)
n=something(20)
print(m+n)

输出:- 30hii

10 到 self.noofpages 和 20 到 b.noofpages

标签: pythonoverloading

解决方案


Ok so a few things to try and clarify this:

1) class definition

A class definition is nothing but a template for the objects derived from it. In that case the class something has two 'special' methods: init() and add().

init(self,...) methods is called as soon as a object is created. In this case when a object of class something is created, it required to be created with an argument that will internally be added to the attribute noofpages of that object (self refers to the object to be created)

add(self,other) method will tell python what to do if two instances of this class type are added, where self refers to the object from where the addition is being called and other refers to another object of the same class.

So after declaring the template for the class two objects of class something are created.

m=something(10)
n=something(20)

These two objects are different instances of class something and so m will have its noofpages set to 10 and n to 20 you can verify this by calling:

print(m.noofpages)
print(n.noofpages)

Now that we established that even though m and n are two different instances of the same class we can move on to the add overload.

First lets talk about the naming convention when overloading addition (it makes the function make more sense). Usually instead of:

def __add__(self,b):
     return str(self.noofpages + b.noofpages)+'hii'

You would have:

def __add__(self,other):
    return str(self.noofpages+other.noofpages)+'hii'

So self refers to the instance of the object where the method is being called and other means another instance of the same type of object.

Finally calling m+n is the same as calling m.__add__(n). So the add method is called on the leftmost element of the addition.

Hope I was more or less clear.


推荐阅读