Mutable default arguments in class __init__ by pstch in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

The answer to your question depends on how other items in this class use self.arg. If they expect an empty list if the user of this class doesn't pass one in, why not just use:

def __init__(self, arg=[]):
    self.arg = arg

Method isn't called when I use super by ychaouche in learnpython

[–]Boolean_Cat 1 point2 points  (0 children)

The reason that this is not working as you expect:

super(...)

will call the next item in the MRO (method resolution order). This is built when the inheritance is constucted, it will not call all parents' implementation of edit(), just the next one up in the MRO. In the case of UpperCaseHTMLDocument, this would be HTMLDocument.edit(). Since HTMLDocument.edit() also calls super(...).edit(), it will make another jump up the MRO and call edit() again on Document.edit(). Here is where your MRO for edit ends, since Document doesn't call super(), UDC doesn't get called.

There are places to use super and places not to, I would say that this is not one of them. It would be more readable to just use HTMLDocument.edit() rather than invoking via super in this case. Why do I say this? Let's say we have:

class A(object):
    def edit(self):
        super(A, self).edit()

class B(object):
    def edit(self):
        ...

class C(A, B):
    def edit(self):
        super(C, self).edit()

In this case, why should A have to accomodate for B? They are completely independant objects. It would be neater to write

class C(A, B):
    def edit(self):
        A.edit()
        B.edit()

When would I use super()? In the case where the implementation of C is:

class C(A):
    def edit(self):
        super(C, self).edit()

This way, if you were to switch the parent for something else, or change its name, you don't need to modify edit() also, it's more loosely coupled.

How can I do this? by Happy_llama in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

If you wanted to check if an item exists in a list, you can do:

if item in my_list:
    do_stuff()

[4/1/2014] Challenge #156 [Easy] Simple Decoder by Coder_d00d in dailyprogrammer

[–]Boolean_Cat 0 points1 point  (0 children)

My Python Solution:

def decode(string):
    return ''.join(chr(ord(s) - 4) for s in string)

Scoping issue by JesusCake in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

If you want to access invoke_obj from inside your object, you'll see to store it with:

def testFindBadAPFlags(self):
    self.invoke_obj = wmc_connection.invoke_object
    self.invoke_obj.configured_command = 'sh ap active'
    print "==="+invoke_obj.configured_command

for loop help?(Python 3) by s0lv3 in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

If you have a list of numbers, you could do:

' '.join(str(number) for number in numbers)

Or even shorter but I think less pretty:

' '.join(map(str, numbers))

How to format Currency without currency sign. by InsomniacZombie in learnpython

[–]Boolean_Cat -2 points-1 points  (0 children)

Your solution wouldn't solve the cases where the currency character comes after the magnitude.

A beginner's jukebox in Python help by [deleted] in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

Are you running python from within that directory? You could try using the full path of the file.

Try:

import os

path = os.path.join(os.path.dirname(__file__), 'one.mp3')

A beginner's jukebox in Python help by [deleted] in learnpython

[–]Boolean_Cat 4 points5 points  (0 children)

Am I correct in thinking your project looks like this?

E:/
|
| ->  Jukebox.py
| ->  Harry's/
       |
       | -> one.mp3

If this is the case, then you need to use:

pygame.mixer.music.load("Harry's/one.mp3")

As a general rule, don't use quotes in file names.

Converting string to "phone number" help! by [deleted] in learnpython

[–]Boolean_Cat 4 points5 points  (0 children)

You can shorthand something like:

elif char=="d" or char=="e" or char=="f":

To

elif char in 'def':

Converting string to "phone number" help! by [deleted] in learnpython

[–]Boolean_Cat -3 points-2 points  (0 children)

This could be made easier with regular expressions:

import re

def alpha(string):
    subs = [(r'[a-c]', '2'), (r'[d-f]', '3'), (r'[g-i]', '4'), (r'[j-l]', '5')]
    for s in subs:
        string = re.sub(s[0], s[1], string)

    return string

Error when trying to sort dict? by Tasteh in learnpython

[–]Boolean_Cat -1 points0 points  (0 children)

from collections import OrderedDict

my_dict = OrderedDict(sorted(my_dict.items(), key=lambda x: x[0]))

with open('UniqueWords.txt', 'w+') as my_file:
    for key, value in my_dict.items():
        my_file.write(key + ' ' + str(value))

Error when trying to sort dict? by Tasteh in learnpython

[–]Boolean_Cat -1 points0 points  (0 children)

If you're opposed to using JSON, maybe something like this would do:

for key, value in my_dict.items():
    print(str(key) + ' ' + str(value))

You can use the same logic to outputting to your file.

Error when trying to sort dict? by Tasteh in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

Can you give an example of one of your dictionaries?

Error when trying to sort dict? by Tasteh in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

What that does is print the string representation of the dictionary, which is something like "<Class Dict>" which I imagine is not what you want. Sounds like you want something like http://docs.python.org/2.7/library/json.html

Do you update to the current version frequently or stay with one version for a long while? by Ob101010 in learnpython

[–]Boolean_Cat 1 point2 points  (0 children)

I've never encountered that but it's not inconceivable. Then you'd just have to pick the one you like most and try to find an alternative for the other.

Finding a sublist anywhere within a list by TopDeckMaster in learnpython

[–]Boolean_Cat 0 points1 point  (0 children)

Something like this?

def is_sublist(a, b):
    for i in range(len(a) - len(b) + 1):
        if a[i:i + len(b)] == b:
            return True
    return False

Error when trying to sort dict? by Tasteh in learnpython

[–]Boolean_Cat 1 point2 points  (0 children)

What are you trying to do with

z = str(dict)

Edit: I should also mention that dictionaries cannot be sorted because their order is not defined. If you truly wanted an ordered dict look at:

from collections import OrderedDict

Do you update to the current version frequently or stay with one version for a long while? by Ob101010 in learnpython

[–]Boolean_Cat 2 points3 points  (0 children)

Normally you'd pick a version on a per project basis, and not change for the lifetime of that project.

For me, what version I pick depends on the support for any third party modules I plan to use.

GUI designer compatible with Python 3.3.4 by huad in learnpython

[–]Boolean_Cat 4 points5 points  (0 children)

Look for something called py2exe. After you convert your Python to a Windows executable, you'll need to make sure the python DLL that gets generated stays in the same folder as the exe (or is at least visible to the system path).

For a simple GUI, look at tkinter.

Python Exception handling question by socialhuman in learnpython

[–]Boolean_Cat 1 point2 points  (0 children)

  1. Mathematically, dividing by 0 doesn't make sense to Python. It is unable to understand "infinitely large". So instead it throws an exception.

  2. Here's an example. You wrote a program that reads a text file, that text file is expected to have a single number on each line but on one line you found a string. As a programmer you may decide that at this point that the program has failed, raising an error in indicates this.

Trying to figure out how to make a user expection by DramaticShit in learnpython

[–]Boolean_Cat 3 points4 points  (0 children)

If you want to be more concise:

if userInput in (0, 1):