Passing Python Argument in Object Oriented Programming

I apologize if this was asked elsewhere, but I do not know how else to formulate this question.

I am a physicist and Python is my first object oriented language. I like this language for its clean code, and somehow everything works as intended (by me;).

However, I have one problem, maybe it’s more a design choice, but since my object-oriented programming is self-learning and very simple, I’m not sure where to go.

So the question is, should I basically pass arguments or manipulate object data directly? Because, for example:

class test(object): ... def dosomething(self, x, y): # do someting with x, y involving a lot of mathematic manipulations def calcit(self): k = self.dosomething(self.x[i], self.y[i]) # do something else with k 

gives a much cleaner code than does not skip x, y , but passes i and writes self explicitly each time. Which do you prefer, or is it an object-oriented paradigm that I break?

In terms of performance, this should not change, since the arguments are passed by reference, right?

+4
source share
2 answers

The paradigm of objects is this: you combine methods and attributes and call them an object.

So, if you are manipulating exactly one of these attributes, you do not need to pass them as parameters, you should use object ones. If you are using something else, you should pass it as parameters.

And nothing prevents you from getting the values ​​of your object into another variable if you are worried about writing yourself every time!

To finish, your function, which takes x and y as parameters, should not be in your object, but outside of it as a helper function, if you really want to do something like this, the reason is that there is no reason to pass your object as the first option (even if it is implicit) if you are not using it.

and yes, the performance will be very similar!

+2
source

should i basically pass arguments or directly manipulate object data.

Think of objects as state systems. If the data belongs to the state of the object, then it must be packed into the object as a member. Otherwise, it should be passed to its methods as an argument.

In your example, what you should do depends on whether you want dosomething by the values ​​of x and y , which are not members of the object. If you do not, you can dosomething to extract x and y from self .

Also, keep in mind that if you are not using self inside a method, then it probably should not be a method at all, but rather an autonomous function.

in terms of performance, this should not change, since the arguments are passed by reference, right?

I would not worry about performance at this point.

+4
source

Source: https://habr.com/ru/post/1382465/


All Articles