■ 메타 클래스를 사용해 특정 클래스 속성 값을 자동 설정하는 방법을 보여준다.
▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
class Field: def __init__(self): self.name = None self.internalName = None def __get__(self, instance, instanceType): if instance is None: return self return getattr(instance, self.internalName, "") def __set__(self, instance, value): setattr(instance, self.internalName, value) class TableRowMeta(type): def __new__(metaClass, className, baseNameTuple, classMemberDictionary): for key, value in classMemberDictionary.items(): if isinstance(value, Field): value.name = key value.internalName = f"_{key}" classInstance = type.__new__(metaClass, className, baseNameTuple, classMemberDictionary) return classInstance class TableRow(metaclass = TableRowMeta): pass class Customer(TableRow): firstName = Field() lastName = Field() prefix = Field() sufix = Field() customer = Customer() print("작업전 :", customer.firstName, customer.lastName, customer.__dict__) customer.firstName = "길동" customer.lastName = "홍" print("작업후 :", customer.firstName, customer.lastName, customer.__dict__) """ 작업전 : {} 작업후 : 길동 홍 {'_firstName': '길동', '_lastName': '홍'} """ |