Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to pass self to an external function

Tags:

python

self

I have a class, A, which is inherited by a bunch of other classes. Some of these have a few functions which are similar and it would be nice to have those functions defined somewhere else and called by the classes that need them. But those functions call functions defined in the super class.

class A():     def imp_func(*args):         # called by the child class functions  Class B(A):     def common_func(self):         # some stuff         self.imp_func(*args) 

So I have created my helper functions which take the self object as an argument and I can call the imp_func from inside the helper functions.

def helper_func(obj, some_args):     # some common stuff     obj.imp_func(*args)  class B(A):     def common_func(self):         # unique stuff         helper_func(self, some_args) 

This solves the problem.

But should I be doing this? Is this Pythonic?

like image 649
elssar Avatar asked Apr 18 '13 13:04

elssar


People also ask

Should I pass self in Python?

Self is a convention and not a Python keyword . self is parameter in Instance Method and user can use another parameter name in place of it. But it is advisable to use self because it increases the readability of code, and it is also a good programming practice.

Why do we pass self in Python method?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.

How do you pass a function to another function?

You can use function handles as input arguments to other functions, which are called function functions . These functions evaluate mathematical expressions over a range of values. Typical function functions include integral , quad2d , fzero , and fminbnd .

Can you pass a list into a function?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.


1 Answers

There is no problem with that whatsoever - self is an object like any other and may be used in any context where object of its type/behavior would be welcome.

In Python, as exemplified by the standard library, instances of self get passed to functions (and also to methods, and even operators) all the time.

like image 86
user4815162342 Avatar answered Sep 19 '22 20:09

user4815162342