Skip to content

Instantly share code, notes, and snippets.

@jrc03c
Last active August 18, 2024 17:17
Show Gist options
  • Save jrc03c/f1211b76916d46494133062412cccfd5 to your computer and use it in GitHub Desktop.
Save jrc03c/f1211b76916d46494133062412cccfd5 to your computer and use it in GitHub Desktop.
create a js-like object in python
# A JS-like object in Python is an object whose properties can be set on-the-fly as in
# JS (i.e., without the need to define a class first).
def JSObject(data={}):
class JSObject:
def __getattr__(self, name):
return data[name]
def __setattr__(self, name, value):
data[name] = value
return JSObject()
person = JSObject()
person.name = "Alice"
person.age = 40
person.say_hi = lambda: "Hi! My name is {}!".format(person.name)
print(person.name) # Alice
print(person.age) # 40
print(person.say_hi()) # Hi! My name is Alice!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment