What is the correct way to call Python methods?

Asked

Viewed 7,326 times

9

What is the correct way to make a method call in Python? As in the example below.

def __init__(self):
   mtd([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])

def mtd(data):
   for value in data:
       print(value)

2 answers

4


Inside the class you must put self, equivalent to $this in PHP, or this in Java in the call of a method, but it has a particularity, is that it is defined that it enters as argument also in the called method, ex:

class Hey():
    def __init__(self):
        self.mtd([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) # indicas que e um metodo interno da class

    def mtd(self, data):
        for value in data:
            print(value)

hey = Hey()

I can’t quite understand the question, but if it’s a method outside the class, do as you were doing:

class Hey():
    def __init__(self):
        mtd([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])

def mtd(data):
    for value in data:
        print(value)

hey = Hey()

3

In Python, every method referring to a class needs to be referenced, in the first parameter, by the pseudo-variable self.

def __init__(self):
   self.mtd([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])

def mtd(self, data):
   for value in data:
       print(value)

The self therefore indicates that mtd belongs to the class containing it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.