Created
June 4, 2025 22:26
-
-
Save ronaldpetty/3463c6f1ecb8c48efe3b26c149035f50 to your computer and use it in GitHub Desktop.
Meta lower + upper
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
class MyMeta(type): | |
def __new__(cls, name, bases, attrs): | |
mod_attrs = {} | |
for attr_name, attr_value in attrs.items(): | |
if attr_name.startswith("__"): | |
mod_attrs[attr_name] = attr_value | |
continue | |
cap_name = attr_name.capitalize() | |
if not callable(attr_value): # If it's a field, wrap it in a property | |
private_name = f"_{cap_name}" | |
def make_getter(n): | |
return lambda self: getattr(self, f"_{n}") | |
def make_setter(n): | |
return lambda self, val: setattr(self, f"_{n}", val) | |
mod_attrs[private_name] = attr_value | |
mod_attrs[cap_name] = property(make_getter(cap_name), make_setter(cap_name)) | |
mod_attrs[attr_name] = property(make_getter(cap_name), make_setter(cap_name)) | |
else: | |
mod_attrs[cap_name] = attr_value | |
return super().__new__(cls, name, bases, mod_attrs) | |
class Dog(metaclass=MyMeta): | |
name = "Maya" | |
breed = "Beagle" | |
def speak(self): | |
return f"{self.Name} says woof!" | |
print(Dog().name) | |
print(Dog().Name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment