0

Let's say I have a class MyClass ... which has a data member x

class MyClass1 :

    def __init__(self) :
        self.x = 1

Also a method which does something with x


Should I pass self.x as a parameter?

class MyClass2 :

    def __init__(self) :
        self.x = 1

    def multiple_of_x(self, x) :
        return x * 2

Or just use self.x within the method?

class MyClass3 :

    def __init__(self) :
        self.x = 1

    def multiple_of_x(self) :
        return self.x * 2

I'm asking which is the more correct approach to object oriented programming?

0

An object is a bundle of state and behavior. The behavior (methods) inherently defaults to having access to the object's state (attributes). As such, it should use that whenever it can.

Think about it this way. If you had a method that needed four or five different pieces of data from the object to return a result, what would happen in each of your cases? In the first case, you'd be passing in those four or five things, every time. And you'd have to get that information from the object itself, resulting in a call like this:

myobj.myfunction(myobj.w, myobj.x, myobj.y, myobj.z)

The second approach would give you this:

myobj.myfunction()

Both give you the same result. The first has a bit more flexibility in case you ever want to pass in something that isn't part of the object. But if that's the case, why would you need the state of the object in the first place?

0

First of all be sure you understand __init__ and self.

The only good reason to pass a value to set x is if x needs to be set. self.x works fine without any help. For that matter so does x.

The only good reason to take self is if you need self. multiple_of_x() doesn't in your first case. But without it, it's a function not a method. It has no access to the object's state. Some people take it anyway just in case they need it.

  • In the example, I am not attempting to set x. I am using x to return another value. So you are saying there would be no reason to ( in the main function, not the class definition ) do this ExampleInstance = myClass() --> ExampleInstance.multiple_of_x(ExampleInstance.x) ? – TT4M.C Jul 26 '16 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.