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__
.
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.
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.
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.
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.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With