-1

I am very new to coding. I want to understand when to use 'self'. Should I always use self when defining a method and call a method?

In the code below, #1 to #5, please help to explan what is wrong and why?

class customer() :
    def __init__(self, name, age, cellNumber): 
        self.name = name
        self.age = age
        self.cellNumber = cellNumber
    def sayHi():   #1
        print("Hi hi!!")
    def info(): #2
        print(self.name + " is "+ str(self.age) + "Number is "+ self.cellNumber)

customer.sayHi() #3
print(brian.age, rex.cellNumber)
print(rex.age)
customer.info(rex)** #4
rex.info()** #5
Guy
  • 46,488
  • 10
  • 44
  • 88
jasonL
  • 65
  • 1
  • 8
  • 1
    Does this answer your question? [What is the purpose of the word 'self', in Python?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self-in-python) or [When do you use 'self' in Python?](https://stackoverflow.com/questions/7721920/when-do-you-use-self-in-python) read [A First Look at Classes](https://docs.python.org/3/tutorial/classes.html#a-first-look-at-classes) as well. – Guy Nov 19 '19 at 07:44
  • Virtually everything in that example is wrong; indentation, missing names, calling instance methods on the class, ... But the short answer is that you need to put at least one parameter in the definition of every instance method, and the convention is to name that parameter self (especially if you're going to refer to it as self in the method's code, as you're doing in info). – jonrsharpe Nov 19 '19 at 07:45

1 Answers1

0

self parameter is the object of class. You should pass it if you declare class method. In other words, you declare that your method belongs to this object passing it to this method. Try to run

def foo(string):
    print(string + ' from function')

class Bar:
    def foo(self, string):
        print(string + ' from ', self)

foo('Hi cruel world')
bar = Bar()
bar.foo('Hi cruel world')

And you'll see

Hi cruel world from function
Hi cruel world from  <__main__.Bar object at 0x000001A0CA120608>

<__main__.Bar object at 0x000001A0CA120608> (the address may be some another) is bar object of Bar class

Pavel Antspovich
  • 1,111
  • 1
  • 11
  • 27