Test if a class is inherited from another [duplicate] - python

This question already has answers here:
How do I check (at runtime) if one class is a subclass of another?
(10 answers)
Closed 4 years ago.
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?

Use issubclass(myclass, parentclass).
In your case:
self.assertTrue( issubclass(QuizForm, forms.Form) )

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()

Related

Calling a method from a constructor in python [duplicate]

This question already has answers here:
Python function calling order
(5 answers)
Closed 3 years ago.
The initial question I had was whether or not a method could be called from a Python constructor. The answer here suggests that it can, but this surprised me some as, based on my reading, python cannot use something that hasn't been previously defined in the code. Looking at the answers in the linked thread, it seems like they are using a method in the constructor that is defined later in the text. How is this possible in python?
Thanks.
When you would be running the code the class would be created , the function wouldn't be called
The function would only be called by object in main function by that time the definition of function would be compiled and known.
Try this
Declare a class and then call a function which is not a member of class * and also not declared
And declare it later , it would throw an error

Why create an empty class, then instantiate it and set some attributes? [duplicate]

This question already has answers here:
Empty class object in Python
(4 answers)
Closed 7 years ago.
html2txt contains the following code:
class Storage: pass
options = Storage()
options.google_doc = False
options.ul_item_mark = '*'
I've not seen such an approach before. What's the benefit/use of this approach over setting up the attributes in __init__(), and is a class even necessary here?
Suppose you want to store some collection of named data. You could use a dict but you like the look of dotted attributes in a class object. Just create the most boring class possible and use python's native attribute assignment to do the trick. It is usually a question of aesthetics.
If you know the attributes ahead of time you can use namedtuples for this kind of functionality.
From the python docs:
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

Python private class fields, how to make? [duplicate]

This question already has answers here:
Does Python have “private” variables in classes?
(15 answers)
Closed 9 years ago.
I'm beginner. In Delphi I can make private field in class: moving it to private section. So ClassVar.Field doesn't exist out of class.
In Python, if I make class
class CName:
testname = 10
then testname can be accessed always. How can I make a field "private"?
You can't!
Naming fields with two underscores will hide it (generate a new name) but you will always be able to access it. Try __testname = 10

List of member variables in a class. [duplicate]

This question already has answers here:
Why is python ordering my dictionary like so? [duplicate]
(3 answers)
Closed 9 years ago.
I am trying to get a list of member variables of a class.
class Book(object):
def __init__(self):
self.title='Inferno'
self.author = 'Dan Brown'
self.publisher= 'DoubleDay'
self.pages=480
bk = Book()
p=bk.__dict__
print p.keys()
The output is:
['publisher', 'author', 'pages', 'title']
I am curious here as the list is neither printedalphabetically nor according to the way I listed the class variables. So in what way does python print it out?
Its completely arbitrary, because it is a dictionary, and a dict is unordered.
(Well, not arbitrary, but more-or-less random, according to the way the computer stores the data).
Python stores class variables in a dict. This is an unordered data structure, so Python is free to choose whatever order it likes.

How do I set a property in python using its string name [duplicate]

This question already has answers here:
How do you programmatically set an attribute?
(5 answers)
Closed 4 months ago.
How can I set an object property given its name in a string? I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this:
for entry in src_dict:
if entry.startswith('can_'):
tgt_obj[entry] = src_dict_profile[entry]
setattr(some_object, 'some_attribute', 42)
Sounds like you're looking for setattr.
Example:
for entry in src_dict:
if entry.startswith('can_'):
setattr(tgt_obj, entry, src_dict_profile[entry])
On objects that have "dict" property
if "__dict__" in dir(obj):
you may do fun things like:
obj.__dict__.update(src_dict)

Categories