How do I adapt, the checkLength() method, to accept any instance attributes I pass to it? For example in this context, I can check either first or last, without hardcoding it inside the checkLength() method?
Any help would be most appreciated.
class Name:
def __init__(self, f, l):
self.first = f
self.last = l
def checkLength(self):
if type(self.first) == str:
return len(self.first)
else:
return False
myName = Name('Sir', 'Mixalot')
print(myName.checkLength())
I have tried the following combinations:
def checkLength(self, last):
if type(self.last) == str:
return len(self.last)
else:
return False
print(myName.checkLength(last))
def checkLength(self.last):
if type(self.last) == str:
return len(self.last)
else:
return False
print(myBody.checkLength(self.last))
Update - trying to use getattr
def __init__(self, f, l):
self.first = f
self.last = l
def checkLength(self, attr):
if type(getattr(self, attr)) == str:
return len(getattr(self, attr))
else:
return False
myName = Name('Sir', 'Mixalot')
print(myName.checkLength(self, "last"))
error =
NameError: name 'self' is not defined````
lenfunction directly? For example:print(len(myName.last))Or, if you need a version oflenwhich checks the type first, you can write this function (typeSafeLen) independently of your class.lenofforl?if isinstance(self.first, str):(allows subclasses) orif type(self.first) is str:(strict test for that exact class). Don't use== str; thestrclass is a singleton, and if you want strict checking, useisfor identity testing, not==(for loose value equality testing).print(myName.checkLength("last"))