In Python, you can use functions as classes. In py, everything is an object. How? I'm no py expert. Here's how we do it!
An Innocent Python Function
a function is like that
def devdotto():
pass
and a class is like that:
class Car:
def __init__(self):
self.wheel = 4
self.make = 'BWM' # i know
def move(self):
print('moving')
more info:
make and wheels are attributes
while move is a method
some tests
car = Car()
print(car.wheel)
print(car.make)
car.move()
gives out
4
BWM
moving
Now Let Us Add Attributes
adding attributes to functions
devdotto.name = 'dev.to'
devdotto.users = 1123234
testing
print(devdotto.name)
print(devdotto.users)
gives out
dev.to
1123234
More Craziness: Adding Methods To Functions
adding an add method:
devdotto.add = lambda x,y: x+y
some info:
testing
print(devdotto.add(1,2))
gives out
3
Conclusion
Since some one liner libs make use of IEF (Immediately Executed Functions) using lambdas to compile even loops, these can be useful, but i can't think of any use cases (for using functions as classes), this said, this is one of py's party tricks, hence the cover image.
img credit: Photo by Jason Leung on Unsplash
Any ideas? Comment them out below!
Top comments (13)
Nice one :)
By the way you can turn classes into functions too:
By the way you can do this:
Great! That's the needed comment to complement this article!
I‘ve written a Python interpreter in Java once where I learned that really everything is an object in python.
I usually ask in job interviews „what’s the difference between Java and Python“ and most candidates say „Java is object-oriented and Python is a scripting language“ :)
you are in language making? really awesome!
Oh no, I only wrote an interpreter that executed precompiled Python code! I did this once as a PoC to run Python on an embedded device. It worked but unfortunately as you might imagine, interpreting Python Byte code in Java which was also interpreted byte code on a slow embedded device was terrible slow.
The point is: I learned how beautifully Python is designed internally.
As you stated: everything’s an object
This is truly amazing!
hum ok, embedded programming is another level for me _
I don't know Abdur.
I understand that you can utilize OOP principles in Python, but if I really want to do OOP AND the scripting lvl I would rather choose Ruby as my language to go. I just hate Python OOP syntax and things associated with the OOP paradigm in Python. Of course, at the end it will work, but I'm really happy to write my scripts without overhead of using OOP in this particular language.
Thanks for the post though, it was good & inspirational :)
ruby i agree is less code, more expressive, but i love the mamothy python
Yep, functions are objects and you can add methods to them. But why would you do that?
to learn more about py i guess
Yeap, that's the coolest reason of all!!
can i make a command button with a class