0

I've a class structure like

class Parent:
   value_type = (object,)
   def __init__(self, value):
      if not isinstance(value, value_type):
          raise ValueError
      self.value = value

class Derived(Parent):
    value_type = (str,)

When I create an instance variable of derived class as

d = Derived(555)

It doesn't raises any error. (The behaviour I need is that it should raise an error in this case as 555 is not a str)

Is there any way to make the parent class constructor use the derived class attribute value_type instead of it's own class attribute?

I know passing value_type as a parameter to __init__ function is a solution, but the value_type should be same throughout the class, so I don't want to redundantly add same value_type field everytime to initialize a derived class instance.

2
  • 2
    This very much does raise an error, namely NameError: name 'value_type' is not defined. Commented Jun 17, 2017 at 9:26
  • Note you should probably raise a TypeError, and ideally with more information. Commented Jun 17, 2017 at 9:30

1 Answer 1

3

The value_type used in Parent is always the value of value_type in the scope, which is whatever you assigned value_type to be in the global scope.

To fix this, use self.value_type to get the value_type assigned to the created instance:

def __init__(self, value):
    if not isinstance(value, self.value_type):
        raise TypeError
    self.value = value
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.