-1
class abc:
    def yo(var):
        a=var
        print(a)
x=abc().yo(5)

Output: Traceback (most recent call last):
File "main.py", line 5, in
x=abc().yo(5)
TypeError: yo() takes 1 positional argument but 2 were given

    class abc:
        def yo(self,var):
            self.a=var
            print(self.a)
    x=abc().yo(5)

Output: 5

it's working till i use the self keyword i mean can we call a function without using self parameter in it why it says yo() takes 1 arguments and is given 2 when we exclude self?

Adam
  • 2,820
  • 1
  • 13
  • 33
Proto Type
  • 47
  • 1
  • 8
  • 4
    `self` is **not** a keyword, it's the *conventional* name for the first parameter to instance methods. If you don't need access to the instance, don't make it an instance method - it can be a static method or just a function. – jonrsharpe Jun 11 '20 at 12:11
  • 2
    If your method does not require `self` that is an indication it should be static https://stackoverflow.com/questions/43587044/do-we-really-need-staticmethod-decorator-in-python-to-declare-static-method – Cory Kramer Jun 11 '20 at 12:12
  • @jonrsharpe self is not a keyword. what is it i mean can we use any other variable inplace? – Proto Type Jun 11 '20 at 12:38
  • Your question in the comment above is already answered in one of the answers below. I just add that static method means the method does not depend neither on the instance, nor on the class, that is why it does not need the `self` nor `cls` in the parameter list. – progmatico Jun 15 '20 at 18:02
  • It is inside the class just because of some *affinity* with it, otherwise it could be just another normal function. – progmatico Jun 15 '20 at 18:03

2 Answers2

3

you have to use decorators to change the first argument in your class methods ,if you don't put any decorator the fuction have the self argument by defaulf (the instance which use this method), if you put the @classmethod decorator like bellow the first argument is cls (the method's class):

class abc:
    a = 'abc'

    @classmethod
    def aFunction(cls, value)
        print(cls.a + value)

the second decorator, probably the one you are looking for allows you to have a class method without default argument:

class abc:
    def __init__(self,value):
        self.value = value

    @staticmethod
    def aFunction(value):
        return value+'abc'
un random
  • 301
  • 1
  • 9
0

self is actually a convention used by since a long time and not a real python keyword. self is nothing but a parameter in function and you can easily use another parameter name in place of it.

Then why use self? Because it is advisable as it increases the readability of code.

Moreover, if the method does not require self, it usually signifies that it should be a static method

Astrian_72954
  • 411
  • 2
  • 11