In the following code, I want metaclass NameMeta to add attribute gender to MyName class in case this class does not declare that 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 output that I am getting:
<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 MyName class as an object in the metaclass so that I can add the attribute?