Feel free to contribute as you see fit.
_
In the interactive python shell, the special variable _ is equivalent to Ans in TI-Basic. It holds the last returned value.

classmethod and staticmethod
Most object oriented Python code doesn't make use of these two, but they're very useful for declaring static functions inside a class. Normally if you have a class definition like so:

Code:

class Blah:
   def blahblah(self, other, arguments):
      dosomething()

blahobj = Blah()
blahobj.blahblah(42, 1337 )

and the interpreter automatically passes blahobj as the self argument to blahblah. Sometimes; however, you want a Java + C style static functions that belong to the whole class, not just to a single instance (generally utility functions related to the purpose of the class). In this case you can declare a function to be a classmethod, which receives the class object it is called on as the implicit first argument; or with staticmethod, which receives no implicit first argument at all. Static methods should be used when the function will always be called on the same class. Class methods should be used when the function will be called on different classes with different implementations of the same function. To declare a class or static method, you have two options. Decorator syntax:

Code:

class Blah:
  @staticmethod
  def staticMethod1():
    print "staticMethod1"

  @classmethod
  def classMethod1(cls):
    print "classMethod1 called on" + str(cls)


or the traditional way:


Code:

class Blah:
  def staticMethod2():
    print "staticMethod2"
  staticMethod2 = staticmethod(staticMethod2)

  def classMethod2(cls):
    print "classMethod2 called on" + str(cls)
  classMethod2 = classmethod(classMethod2)


unpacking + zip
say you want to return multiple values from a function.

Code:

def getMinMedianMax(list):
   return (min(list), max(list), sorted(list)[len(list) / 2])

list = (1, 3, 6, 6, 9, 2)
min, median, max = getMinMedianMax(list)

min = 1
median = 6
max = 9

This works for tuples and lists.

if for some strange reason you want one-tuples, you can create them like this:

Code:
onetuple = (1, )

and to unpack the one-tuple

Code:
firstval, = onetuple


You can also unpack lists, tuples, and dictionaries into a function call.

Code:

def sumTwoValues(one, two):
  return one + two
list = [1, 2]
sum = sumTwoValues(*list)


to pack an arbitrary number of arguments into a list you can do the reverse.

Code:

def sumArgs(*args):
   return sum(args)
sum = sumArgs(1, 2, 3)


The same works for dictionaries and keyword arguments. It's hard to think of trivial examples for keyword arguments, so for this I'm just gonna link you to the python tutorial. http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html

Because python is an interpreted language, you can actually dump your programs configuration settings to a text file, and then use the eval() function to read it back later. This should be used with caution, since eval will execute any valid python code in the input.


One last thing: zip(). It will take its arguments and zip them together. The easiest way to explain this is to see it in action.

Code:

l1 = [1, 2, 3]
l2 = [4, 5, 6]
zlist = zip(l1, l2)

At this point, zlist equals [(1, 4), (2, 5), (3, 6)]. To unzip this back into it's constituent parts, you can do this:

Code:

l2, l1 = zip(*zlist)

l2 now equals [1, 2, 3] and l1 now equals [4, 5, 6]

list comprehensions
basically, a one-line way of building a list from some input.
for example, say you want a list of the ascii values of every character in a string.

Code:

input = "Omghaiguys"
output = [ord(letter) for letter in input]

output would now equal [79, 109, 103, 104, 97, 105, 103, 117, 121, 115]

You can also conditionally include parts of the list. For example, to remove all the vowels from a string you could do this.

Code:

input = "Omghaiguys"
output = "".join([letter for letter in input if letter.lower() not in "aeiou"])

output would now equal "mghgys"

magic slicing
Most of you should be aware of the ability to slice to the end of a list, or from the beginning of a list (e.g. list[:5] is equivalent to list[0:5] and list[5:] is equivalent to list[5:len(list)]), but there are a couple additional features that are nice. you can use a negative list index to get the last n items in a list. For example list[-5:] will retrieve the last 5 items in a list, and list[:-5] will retrieve all but the last 5. Better still is slicing with 2 colons. list[2::3] will retrieve every 3rd item in list, starting from an index of 2. For example

Code:

range(100)[2::3]

will return every multiple of 3 between 0 (inclusive) and 100 (exclusive), or to use mathematical notation all multiples of 3 in [0, 100).
Python scares me...
magicdanw wrote:
Python scares me...


care to elaborate? Anything in particular that scares you?
I think a lot of it is the dynamic typing. It seems useless, inefficient, and could encourage one to code without thinking ahead.

Also, I like curly braces... Laughing
magicdanw wrote:
I think a lot of it is the dynamic typing. It seems useless, inefficient, and could encourage one to code without thinking ahead.

It's not just dynamic typing (variables can hold values of any type), it's Duck typing, which means that types are essentially irrelevant. Basically you can imitate class A closely enough with class B to pass objects of type B to a function that needs objects of type A without having to extend A.

magicdanw wrote:
Also, I like curly braces... 0x5

The only thing I really miss from C-ish languages is the ?: operator, although I just had a brainwave for how to implement it Very Happy

Not having {} leads to much more structured source code, which is a huge boon in preventing code-rot.
elfprince13 wrote:
magicdanw wrote:
I think a lot of it is the dynamic typing. It seems useless, inefficient, and could encourage one to code without thinking ahead.

It's not just dynamic typing (variables can hold values of any type), it's Duck typing, which means that types are essentially irrelevant. Basically you can imitate class A closely enough with class B to pass objects of type B to a function that needs objects of type A without having to extend A.
Is that supposed to alleviate my fears? Razz If I have no clue if I have a duck or not, I have no business passing it to a method that utilizes ducks!

elfprince13 wrote:
Not having {} leads to much more structured source code, which is a huge boon in preventing code-rot.
How is that? Braces mark which code is related to a certain header quite well, IMO.
magicdanw wrote:
Is that supposed to alleviate my fears? Razz If I have no clue if I have a duck or not, I have no business passing it to a method that utilizes ducks!

the rationale behind duck typing is that if it walks like a duck, swims like a duck, and quacks like a duck you shouldn't care if its a duck or not.

magicdanw wrote:
How is that? Braces mark which code is related to a certain header quite well, IMO.


compare:


Code:

public int doSomeStuff(int i, int b){ i++; b++; i = i*b - 35;
               b = Math.pow(b, 2);
   return i - b
}



Code:

def doSomeStuff(i, b):
    i += 1
    b += 1
    i = i * b - 35
    b = b ** 2
    return i - b


obviously the first example *could* be structured just as nicely, but we also all know that it won't always be, and everyone has different standards as to how they like code to be laid out when you use curly-braces.

Code:

public int doSomeStuff(int i, int b){ i++; b++; i = i*b - 35;
               b = Math.pow(b, 2);
   return i - b
}
This makes me cringe sooooo hard. My code is never like that. I actually feel strong emotions against people who don't indent an opening brace correctly. Observe how my code looks with braces:

Code:

public int doSomeStuff(int i, int b)
{
    i++; b++; i = i*b - 35;
    b = Math.pow(b, 2);
    return i - b
}

There, now isn't that nice?

As for the code without braces... Imagine if HTML were like that? Or BBCode? Instead of wrapping things in tags, you just prefaced them with a header. Imagine how quickly things would get ugly!
magicdanw wrote:
This makes me cringe sooooo hard. My code is never like that. I actually feel strong emotions against people who don't indent an opening brace correctly. Observe how my code looks with braces:

Code:

public int doSomeStuff(int i, int b)
{
    i++; b++; i = i*b - 35;
    b = Math.pow(b, 2);
    return i - b
}

There, now isn't that nice?

I agree, unfortunately not everyone is so well mannered Razz Thankfully Python forces well-manneredness

magicdanw wrote:
As for the code without braces... Imagine if HTML were like that? Or BBCode? Instead of wrapping things in tags, you just prefaced them with a header. Imagine how quickly things would get ugly!

HTML and BBCode aren't programming languages, they're markup languages, which have a drastically different use, though quite honestly, I wish HTML did force polite indentation, because a lot of sites are pretty dirty looking if you read through the source.
My favorite variety of Python crack is Django. With just 4 lines of code, I can implement and interface a new object into my templates.
Very Happy
magicdanw wrote:

Code:

public int doSomeStuff(int i, int b)
{
    i++; b++; i = i*b - 35;
    b = Math.pow(b, 2);
    return i - b
}


It is the same thing in python, just drop the braces. Oh, and you missed the ; after the return statement Wink (see, python would have saved you, since they aren't needed Smile )


Code:

def doSomeStuff(i, b):
    i += 1; b += 1; i = i*b - 35;
    b = math.pow(b, 2);
    return i - b


And yes, the above actually runs in python. Semi-colons are perfectly acceptable in python. Go ahead, copy/paste it into an interpreter (after "import math", of course)

Oh, and you can get "strong" typing in Python. I had a code snippet somewhere here that you could something along the lines of


Code:
@filter(int,(int,float))
def blah(a, b):
   pass


And it would only allow you to pass in a type of 'int' for the first parameter, but the second parameter could take a type of 'int' or 'float'

@Elf: You mentioned list comprehensions, what about dictionary comprehensions? Don't be hating now

My favorite uses of python are its extreme flexibility at runtime. For example:


Code:
>>> class foo:
...     __name__ = "wouldn't you like to know"
...
>>> f = foo()
>>> def t(self):
...     print(self.__name__)
...
>>> f.printName = types.MethodType(t,f)
>>> f.printName()
wouldn't you like to know


Now that is self modifying code Wink

Or the ability to override just about anything. Example:

Code:
>>> class foo:
...     def __getattr__(self, attr):
...             return "Get it yourself, yeesh..."
...
>>> f = foo()
>>> print(f.hello)
Get it yourself, yeesh...
>>>
Kllrnohj wrote:
magicdanw wrote:

Code:

public int doSomeStuff(int i, int b)
{
    i++; b++; i = i*b - 35;
    b = Math.pow(b, 2);
    return i - b
}


It is the same thing in python, just drop the braces. Oh, and you missed the ; after the return statement Wink (see, python would have saved you, since they aren't needed Smile )
I left it out cause Elfprince did in his original example. Perhaps Python is making him too complacent to program in other languages? Wink
magicdanw wrote:
I left it out cause Elfprince did in his original example. Perhaps Python is making him too complacent to program in other languages? Wink

Don't even talk until you switch from writing utility scripts in Python to multi-threaded data processing apps in Java (not my choice, requirement of the research project). <bad pun>That's what we call a "jar"ring transition </bad pun>


@Kllrnohj: I haven't used Python 3.0 yet, so no dict or set comprehensiony goodness for me.
elfprince13 wrote:
@Kllrnohj: I haven't used Python 3.0 yet, so no dict or set comprehensiony goodness for me.


You are missing out. Check out this hotness:


Code:
>>> class book:
...     author = "bob"
...     title = "python is awesome"
...
>>> b = book()
>>> print("Book: '{0.title}' by {0.author}".format(b))
Book: 'python is awesome' by bob
>>>


Format, of course, takes a variable number of arguments. First argument is {0}, second is {1}, etc....
Oooh, that's actually quite nice. I was going to ridicule with:


Code:
struct book{
      char *author;
      char *title;
} b;

b.title = "python is awesome";
b.author = "bob";

printf("Book: '%s' by %s",b.title,b.author");
to show that even in C it's not that bad, but that's cute too.
Kllrnohj wrote:
elfprince13 wrote:
@Kllrnohj: I haven't used Python 3.0 yet, so no dict or set comprehensiony goodness for me.


You are missing out. Check out this hotness:


Code:
>>> class book:
...     author = "bob"
...     title = "python is awesome"
...
>>> b = book()
>>> print("Book: '{0.title}' by {0.author}".format(b))
Book: 'python is awesome' by bob
>>>


Format, of course, takes a variable number of arguments. First argument is {0}, second is {1}, etc....


Reasonably cool, but why use format() instead of just print("Book: '%s' by %s" % (b.author, b.format))
elfprince13 wrote:
Reasonably cool, but why use format() instead of just print("Book: '%s' by %s" % (b.author, b.format))


Because then you have to specify the type, and that just doesn't make sense in a duck typed language. The {n} method doesn't care what type of object you give it. I could have passed in anything for {0}, and I don't have to reflect that in the print string. Also, you are passing in 2 objects, I only had to pass in one Wink

KermMartian wrote:
to show that even in C it's not that bad, but that's cute too.


yeah, but again, you have to know the type, and in C if you get the type wrong you don't get an error stating as such, you get a hard crash. Heck, C++ has an output that doesn't require the type to be specified, so its about time Python caught up in that regard Very Happy
Kllrnohj wrote:
Because then you have to specify the type, and that just doesn't make sense in a duck typed language. The {n} method doesn't care what type of object you give it. I could have passed in anything for {0}, and I don't have to reflect that in the print string. Also, you are passing in 2 objects, I only had to pass in one Wink


How do you deal with formatting numbers that you want rounded to some number of significant digits?
elfprince13 wrote:
How do you deal with formatting numbers that you want rounded to some number of significant digits?



Code:
>>> print("{0:0.2f}".format(1.1123123))
1.11

>>> for i in range(6):
...     print("{0:0.{1}f}".format(1.1123123, i))
...
1
1.1
1.11
1.112
1.1123
1.11231


There are a *lot* of cool things that the new format can do. Check it out here: http://www.python.org/dev/peps/pep-3101/
Razz so you *do* still have to tell it what kind of formatting you want. granted, being able to pass in an object is a cool, but I'm having trouble envisioning a situation where that would be more useful than the old way of doing it.
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 2
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement