List of member variables in a class. [duplicate] - python

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.

Related

In Python3 How to make a user defined class object can get element by index ( obj[ i ] )? [duplicate]

This question already has answers here:
Implement list-like index access in Python
(2 answers)
Closed 5 years ago.
In python, list, string, tuple can be got element by using index (obj[i]), just like C++. In the same way is there any method like override operators to make user-defined class' object be able to get element by using square-bracket []?
For example:
>>>obj = user_class([1,2,4])
>>>obj[0]
1
>>>obj[1]
2
the way user_class=list or user_class=tuple can't be a solution, because I have to add a series of control code in this this class. And the way that this class work is totally different from list or tuple.
Is there anyone know the solution?
You should implement a __getitem__ method in the user_class.
class user_class:
def __init__(self, lst):
self.values = lst
def __getitem__(self, it):
return self.values[it]
Or it can be a subclass of some base type like list:
class user_class(list):
# your control code goes here
def shout(self):
print("AAA!")

Can a dictionary be used to pass variables to a function? [duplicate]

This question already has answers here:
Passing a dictionary to a function as keyword parameters
(4 answers)
Closed 5 years ago.
I have a class with an init function that needs ~20 variables passed to it. Instantiations of the class are rather ugly:
some_var = MyClass(param1=mydict('param1')
param2=mydict('param2')
param3=mydict('param3')
...
param20=mydict('param20')
I keep all of those parameters in a dictionary for easy handling already. Not all parameters are necessary so I don't want the class to accept only a dictionary object I don't think.
I'm wondering if I there's a nice trick to clean this up by specifying that the parameters to init are to be taken from the dictionary?
I'm just looking for tips and tricks on tidying this up a little. I have quite a few long/ugly instantiations of this class.
You can use keyword argument expansion:
some_var = MyClass(**mydict)

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

Test if a class is inherited from another [duplicate]

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

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