Write Python in Javascript Style
Some Javascript practices are good, up to your taste. This article demonstrates some examples how to write Python in the fashion of Javascript.
Dynamic Object
Javascript
Python
class Namespace:
pass
a = Namespace()
a.v = 1
print(a.v)
def hello():
print('hello')
a.f = hello
a.f()
# another object
b = Namespace()
We just need to create an empty class as a class is a namespace and allows you to set attributes.
Note you cannot use a = {} to achieve the same as js because dict object don't allows you to set attributes (no __setattr__ function).
a = {}
a.v = 1
AttributeError Traceback (most recent call last)
line 2
1 a = {}
----> 2 a.v = 1
AttributeError: 'dict' object has no attribute 'v'
But adding a function as an instance method, i.e. with self, is different. You need to use types.MethodType.
import types
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof!"
# Create an instance
dog = Dog("Buddy")
# Define a new method that we want to add to this instance only
def roll_over(self):
return f"{self.name} rolls over!"
# Bind the function to the instance as a method
dog.roll_over = types.MethodType(roll_over, dog)
# Now the instance has the new method
print(dog.speak()) # Buddy says woof!
print(dog.roll_over()) # Buddy rolls over!