Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a class is inherited from another [duplicate]

This question is more Python related than Django related. I want to test write a test for this function that I am using to get a Django form dynamically with the fields I set.

def quiz_form_factory(question):     properties = {         'question': forms.IntegerField(widget=forms.HiddenInput, initial=question.id),         'answers': forms.ModelChoiceField(queryset=question.answers_set)     }     return type('QuizForm', (forms.Form,), properties) 

I want to test if, the QuizForm class returned is inherited from forms.Form.

Something like:

self.assertTrue(QuizForm isinheritedfrom forms.Form)  # I know this does not exist 

Is there any way to do this?

like image 989
Renne Rocha Avatar asked Apr 11 '11 22:04

Renne Rocha


People also ask

How do you check if a class inherits from another class python?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

How do you check for inheritance in Python?

Two built-in functions isinstance() and issubclass() are used to check inheritances. The function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each and every class in Python inherits from the base class object .

How can you tell if an object is inherited from a specific class?

You can compare two objects to determine the relationship, if any, between the classes from which they are created. The IsInstanceOfType method of the System. Type class returns True if the specified class inherits from the current class, or if the current type is an interface supported by the specified class.

Can a class inherit from another class?

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).


2 Answers

Use issubclass(myclass, parentclass).

In your case:

self.assertTrue( issubclass(QuizForm, forms.Form) ) 
like image 186
pajton Avatar answered Oct 16 '22 22:10

pajton


Use the built-in issubclass function. e.g.

issubclass(QuizForm, forms.Form) 

It returns a bool so you can use it directly in self.assertTrue()

like image 29
bradley.ayers Avatar answered Oct 16 '22 21:10

bradley.ayers