Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it un-pythonic to define a function inside of a class method?

Tags:

python

PyLint told me that one of my class methods didn't need to be a method, but could just be a function in a class since it didn't use any class attribute. That made me do things I thought were "bad," but maybe they are Pythonic. Is the following code what Python wants us to do?

class TestClass(ParentClass):
    def __init__(self):
        def callbackfunction(text):
            print("hello")
        ParentClass.map_event_to_callback(ParentClass.event, callbackfunction)

where ParentClass.event emits text to its callback, but we'll just ignore that print "hello" instead. Even simpler:

class TestClass():
    def __init__(self, text):
        def printhello(text):
            print("hello")
        printhello(text)

assuming I don't care about text or printhello after __init__.

like image 261
Scott Howard Avatar asked Mar 09 '16 00:03

Scott Howard


People also ask

Can I define a function inside a method Python?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.

Can we define a function inside a class in Python?

A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.

Can I define a function inside a method?

You cannot (and in Java they are called methods). You can, however, define an anonymous class inside of a method, and call its methods. As I see it, there is a difference between methods and functions, while functions live by themselves, methods are related to class or object.

What is a function inside a class called?

In c++ a function contained within a class is called the member function. A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.


1 Answers

Creating a nested function for a callback is just fine. It even gives that function access to any locals in the parent function (as closures).

You can use a lambda if all you need to execute is one expression:

class TestClass(ParentClass):
    def __init__(self):
        ParentClass.map_event_to_callback(ParentClass.event, lambda text: print("hello"))
like image 156
Martijn Pieters Avatar answered Oct 05 '22 23:10

Martijn Pieters