In the following code, I want the metaclass NameMeta add a gender attribute to the MyName class if this class does not declare this attribute.
class NameMeta(type): def __new__(cls, name, bases, dic): if 'gender' not in dic: setattr(name, 'gender', 'Male') return super().__new__(cls, name, bases, dic) class MyName(metaclass=NameMeta): def __init__(self, fname, lname): self.fname = fname self.lname = lname def fullname(self): self.full_name = self.fname + self.lname return self.full_name inst = MyName('Joseph ', 'Vincent') print(MyName.gender)
This is the result I get:
<ipython-input-111-550ff3cfae41> in __new__(cls, name, bases, dic) 2 def __new__(cls, name, bases, dic): 3 if 'gender' not in dic: ----> 4 setattr(name, 'gender', 'Male') 5 return super().__new__(cls, name, bases, dic) 6 AttributeError: 'str' object has no attribute 'gender'
I know this error makes sense since name is a string. My question is: how can I access the MyName class as an object in a metaclass to add an attribute?
source share