What is the correct way to call methods in Python?

6

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)
    
asked by anonymous 09.01.2017 / 19:59

2 answers

2

Within 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, 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 not understand the question well, but if it is a method external to the class, you 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()
    
09.01.2017 / 20:02
2

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

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 that contains it.

    
09.01.2017 / 20:23