I have defined a base class that handles generic content, and children classes that are more specific in which content (object type) they accept. However, when calling the function defined in the parent class, the parent variables are used instead of the child variables. How do I get Python to use the child variable inside the parent functions ?
Example code :
class BaseField(object):
__accepted_types = (object,)
def __init__(self, description=""):
self.content = None
self.description = description
def set(self, content):
if isinstance(content, self.__accepted_types):
print(type(content), self.__accepted_types)
print(type(self))
self.__set(content)
else:
raise ValueError("wrong type")
def __set(self, content):
pass
class StringField(BaseField):
__accepted_types = (basestring,)
def __init__(self, description=""):
super().__init__(description)
print(self.__accepted_types)
if __name__ == '__main__':
x = StringField("a test field")
x.set(3)
I expect this code to raise a ValueError
(I'm trying to pass an int
to a class that only accepts str
), however I get the following result:
(<class 'str'>,)
<class 'int'> (<class 'object'>,) <class '__main__.StringField'>
Note that the function correctly returns that it's within "StringField"
but uses the "BaseField"
value for __accepted_types
. The behavior is the same if I declare __accepted_types
as an instance variable.