Python Forum
Is it necessary to pass value of 'self' ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it necessary to pass value of 'self' ?
#6
If you write a class, then do it right.
You're able to change the behavior of classes.
For example, you can add a method for add and subtract.

With your provided example:
class MyValue:
    def __init__(self, value):
        self.value = value
    def __add__(self, other):
        '''I am method in class Mathematics and not a function'''
        return self.value + other.value
 
    def __sub__(self, other):
        return self.value - other.value


my_val1 = MyValue(5)
my_val2 = MyValue(4)

print(my_val1 + my_val2)
Output:
9
And if you want to have functions, which takes left and right operand and doing something with it, then just use regular functions.

def add(a, b):
    return a + b


def sub(a, b):
    return a - b

# or use operator add and sub from operator module:

from operator import add, sub

print(add(1,2))
print(add(2,3))
Output:
from operator import add, sub print(add(1,2)) print(add(2,3))
I guess you wanted the class, to stick the methods together.
If you have a regular method, then you have to instantiate the class to access the method.
A staticmethod does not supply the function with a reference to self nor to class.
To use this method, the class must be instantiated.

Finally, the classmethod allows calling methods directly on a class without creating an instance.

class Math:
    @classmethod
    def add(cls, a, b):
        return a + b

    @classmethod
    def sub(cls, a, b):
        return a - b


# calling the method on the class directly
print(Math.sub(1,2))
Output:
-1
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Is it necessary to pass value of 'self' ? - by DeaD_EyE - Jul-13-2020, 07:36 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to pass encrypted pass to pyodbc script tester_V 0 919 Jul-27-2023, 12:40 AM
Last Post: tester_V
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,604 Sep-07-2020, 08:02 AM
Last Post: perfringo
  Pass by reference vs Pass by value leodavinci1990 1 2,260 Nov-20-2019, 02:05 AM
Last Post: jefsummers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020