Last active
August 18, 2024 17:17
-
-
Save jrc03c/f1211b76916d46494133062412cccfd5 to your computer and use it in GitHub Desktop.
create a js-like object in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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