Marco8963
Marco8963

Reputation: 11

Why do I have to pass an argument on every method call?

I don't have to pass self but I have to pass master in line 4 of the the following code.

import game
window = game.Window()
cluster = game.Cluster(window)
cluster.circle(**window**,10,10,5)


. . .
class Cluster(Window):
    def __init__(self,master):
        self.obj = []
        self.x = []
        self.y = []
        self.hitbox = master.canvas.create_rectangle(0,0,0,0)
    def update(self,master):
        master.canvas.coords(self.hitbox,min(self.x)-2,min(self.y)-2,max(self.x)+2,max(self.y)+2)
    def circle(self,master,x,y,r):
        self.obj += [master.canvas.create_oval(x-r,y-r,x+r,y+r)]
        self.x += [x-r,x+r]
        self.y += [y-r,y+r]
        self.update(master)

Upvotes: 1

Views: 123

Answers (1)

BartoszKP
BartoszKP

Reputation: 35891

Change your code to store the value of master as an instance attribute:

class Cluster(Window):
    def __init__(self,master):
        self.obj = []
        self.x = []
        self.y = []
        self.hitbox = master.canvas.create_rectangle(0,0,0,0)
        self.master = master

    def update(self):
        self.master.canvas.coords(self.hitbox,min(self.x)-2,min(self.y)-2,max(self.x)+2,max(self.y)+2)

    def circle(self,x,y,r):
        self.obj += [self.master.canvas.create_oval(x-r,y-r,x+r,y+r)]
        self.x += [x-r,x+r]
        self.y += [y-r,y+r]
        self.update()

So you don't have to pass it along to each method.

self gets a special treatment in Python and it's passed implicitly (https://docs.python.org/3/tutorial/classes.html#classes):

In C++ terminology, normally class members (including the data members) are public (except see below Private Variables), and all member functions are virtual. As in Modula-3, there are no shorthands for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call. As in Smalltalk, classes themselves are objects. This provides semantics for importing and renaming. Unlike C++ and Modula-3, built-in types can be used as base classes for extension by the user. Also, like in C++, most built-in operators with special syntax (arithmetic operators, subscripting etc.) can be redefined for class instances.

Even more strictly speaking: the first argument - technically you can name it whatever you want (https://docs.python.org/3/tutorial/classes.html#random-remarks):

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

Upvotes: 2

Related Questions