As I'm reading the Django documentation, I see this in the example:  from django.db import models  class HandField(models.Field):      description = "A hand of cards (bridge style)"      def __init__(self, *args, **kwargs):         kwargs['max_length'] = 104         super(HandField, self).__init__(*args, **kwargs)   I dont understand why the call to super is:  super(HandField, self).__init__(*args, **kwargs)   whereas (coming from C programming) I thought it should be:  super(HandField, self).__init__(args, kwargs)   How comes?  Yes. And I'm not asking what mean "*" and "**" (link marked as a duplicate), I'm asking why it's not re-sent without the star = why it's re-sent to parent with the stars, which means to me: "dictionary of a dictionary". And my question is different from the duplicate link, and the duplicate link doesnt answer to my question.
866
In the following method definitions, what does the * and ** do for param2?  def foo(param1, *param2): def bar(param1, **param2):
56384
When declaring a template, I am used to having this kind of code:  template &lt;class T&gt;   But , they used:  template &lt;unsigned int N&gt;   I checked that it compiles. But what does it mean? Is it a non-type parameter? And if so, how can we have a template without any type parameter?
119696
In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.  Suppose that you want create a subclass of OptionParser that overrides only a single method (for example exit()). In Java you can write something like this:  new OptionParser () {      public void exit() {         // body of the method     } };   This piece of code creates a anonymous class that extends OptionParser and override only the exit() method.  There is a similar idiom in Python? Which idiom is used in these circumstances?
5812
Why does the  exist in modern languages such as C# and Java? Is it purely a self documenting code feature, or does it serve any actual purpose?  For instance the following example:  Class1 obj = new Class1();  Class1 foo() {     return new Class1(); }   Is as easy to read as the more Pythonesque way of writing it:  Class1 obj = Class1();  Class1 foo() {     return Class1(); }   EDIT:  hit the nail on the head with the clarification of the question: Why did they choose this syntax?
80088
When referencing class variables, why do people prepend it with this? I'm not talking about the case when this is used to disambiguate from method parameters, but rather when it seems unnecessary.  Example:  public class Person {             private String name;      public String toString() {         return this.name;     } }   In toString, why not just reference name as name?  return name;   What does this.name buy?   a stackoverflow question whose code has this pre-pending.
14937
Sometimes it seems natural to have a default parameter which is an empty list. Yet . If for example, I have a function: def my_func(working_list=[]):     working_list.append(&quot;a&quot;)     print(working_list)  The first time it is called the default will work, but calls after that will update the existing list (with one &quot;a&quot; each call) and print the updated version. So, what is the pythonic way to get the behavior I desire (a fresh list on each call)?
7441
Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value, then why can't we do the same for local variables?  And it also leads to problems as explained in :     Well this rule is most frustrating when trying to close a resource in a finally block. If I instantiate the resource inside a try, but try to close it within the finally, I get this error. If I move the instantiation outside the try, I get another error stating that a it must be within a try.      Very frustrating.
102717
Given the Python function:  def a_method(arg1, arg2):     pass   How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2").  The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed "a,b" when I call a_method("a", "b")?
8793
What exactly do *args and **kwargs mean?  According to the Python documentation, from what it seems, it passes in a tuple of arguments.  def foo(hello, *args):     print hello      for each in args:         print each  if __name__ == '__main__':     foo("LOVE", ["lol", "lololol"])   This prints out:  LOVE ['lol', 'lololol']   How do you effectively use them?
123257
Is it true, that the Asterisk always means "Hey, that is a pointer!" And an Pointer always holds an memory adress?  (Yes I know for the exception that a * is used for math operation)  For Example:   NSString* myString;   or  SomeClass* thatClass;   or  (*somePointerToAStruct).myStructComponent = 5;   I feel that there is more I need to know about the Asterirsk (*) than that I use it when defining an Variable that is a pointer to a class.  Because sometimes I already say in the declaration of an parameter that the Parameter variable is a pointer, and still I have to use the Asterisk in front of the Variable in order to access the value. That recently happened after I wanted to pass a pointer of an struct to a method in a way like [myObj myMethod:&amp;myStruct], I could not access a component value from that structure even though my method declaration already said that there is a parameter (DemoStruct*)myVar which indeed should be already known as a pointer to that demostruct, still I had always to say: "Man, compiler. Listen! It IIISSS a pointer:" and write: (*myVar).myStructComponentX = 5;  I really really really do not understand why I have to say that twice. And only in this case.  When I use the Asterisk in context of an NSString* myString then I can just access myString however I like, without telling the compiler each time that it's a pointer. i.e. like using *myString = @"yep".  It just makes no sense to me.
54282
Given a class:  from django.db import models  class Person(models.Model):     name = models.CharField(max_length=20)   Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments?  For example:   # Instead of:  Person.objects.filter(name__startswith='B')  # ... and:  Person.objects.filter(name__endswith='B')   # ... is there some way, given:  filter_by = '{0}__{1}'.format('name', 'startswith')  filter_value = 'B'   # ... that you can run the equivalent of this?  Person.objects.filter(filter_by=filter_value)  # ... which will throw an exception, since `filter_by` is not  # an attribute of `Person`.
103588
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:  "[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"   Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:  print 'my list is %s'%(list)   it looks something like this:  [&lt;__main__.cell instance at 0x2a955e95f0&gt;, &lt;__main__.cell instance at 0x2a955e9638&gt;, &lt;__main__.cell instance at 0x2a955e9680&gt;]   how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?
107434
I was looking at the Proxy Pattern, and to me it seems an awful lot like the Decorator, Adapter, and Bridge patterns. Am I misunderstanding something? What's the difference? Why would I use the Proxy pattern versus the others? How have you used them in the past in real world projects?
59036
Say I have the following in my models.py:  class Company(models.Model):    name = ...  class Rate(models.Model):    company = models.ForeignKey(Company)    name = ...  class Client(models.Model):    name = ...    company = models.ForeignKey(Company)    base_rate = models.ForeignKey(Rate)   I.e. there are multiple Companies, each having a range of Rates and Clients.  Each Client should have a base Rate that is chosen from it's parent Company's Rates, not another Company's Rates.  When creating a form for adding a Client, I would like to remove the Company choices (as that has already been selected via an "Add Client" button on the Company page) and limit the Rate choices to that Company as well.  How do I go about this in Django 1.0?    My current forms.py file is just boilerplate at the moment:  from models import * from django.forms import ModelForm  class ClientForm(ModelForm):     class Meta:         model = Client   And the views.py is also basic:  from django.shortcuts import render_to_response, get_object_or_404 from models import * from forms import *  def addclient(request, company_id):     the_company = get_object_or_404(Company, id=company_id)      if request.POST:         form = ClientForm(request.POST)         if form.is_valid():             form.save()             return HttpResponseRedirect(the_company.get_clients_url())     else:         form = ClientForm()      return render_to_response('addclient.html', {'form': form, 'the_company':the_company})   In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:  manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]    seems promising but I don't know how to pass in the_company.id and I'm not clear if that will work outside the Admin interface anyway.  Thanks.  (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)
30376
Let's say you have a class called Customer, which contains the following fields:   UserName Email First Name Last Name   Let's also say that according to your business logic, all Customer objects must have these four properties defined.  Now, we can do this pretty easily by forcing the constructor to specify each of these properties.  But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object.    I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them.  But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.  Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?
110498
That's it. If you want to document a function or a class, you put a string just after the definition. For instance:  def foo():     """This function does nothing."""     pass   But what about a module? How can I document what a file.py does?
94067
I can't find a definitive answer for this. As far as I know, you can't have multiple __init__ functions in a Python class. So how do I solve this problem? Suppose I have a class called Cheese with the number_of_holes property. How can I have two ways of creating cheese objects...  One that takes a number of holes like this: parmesan = Cheese(num_holes = 15) And one that takes no arguments and just randomizes the number_of_holes property: gouda = Cheese()  I can think of only one way to do this, but this seems clunky: class Cheese():     def __init__(self, num_holes = 0):         if (num_holes == 0):             # Randomize number_of_holes         else:             number_of_holes = num_holes  What do you say? Is there another way?