相关疑难解决方法(0)

为什么在声明时执行Button参数"command"?

我的代码是:

from Tkinter import *

admin = Tk()
def button(an):
    print an
    print 'het'

b = Button(admin, text='as', command=button('hey'))
b.pack()
mainloop()
Run Code Online (Sandbox Code Playgroud)

按钮不起作用,在没有我的命令的情况下打印'hey'和'het'一次,然后,当我按下按钮时没有任何反应.

python tkinter

60
推荐指数
3
解决办法
2万
查看次数

有没有办法将函数存储在列表或字典中,以便在调用索引(或键)时触发存储的函数?

例如,我尝试了类似的东西mydict = {'funcList1': [foo(),bar(),goo()], 'funcList2': [foo(),goo(),bar()],但是没有用.

有这种功能的某种结构吗?

我意识到我可以用一堆def语句轻松地做到这一点:

def func1():
    foo()
    bar()
    goo()
Run Code Online (Sandbox Code Playgroud)

但是我需要的陈述数量变得非常笨拙且难以记住.将它们很好地包装在字典中会很好,我可以一次又一次地检查键.

python dictionary dispatch

48
推荐指数
1
解决办法
6万
查看次数

Tkinter使用lambda循环分配按钮命令

我正在尝试创建一些按钮(带有for),如下所示:

def a(self, name):
    print name

users = {"Test":"127.0.0.0", "Test2":"128.0.0.0"}
row = 1
for name in users:
    user_button = Tkinter.Button(self.root,
                                 text=name,
                                 command=lambda: self.a(name))
    user_button.grid(row = row, column = 0)
    row+=1
Run Code Online (Sandbox Code Playgroud)

并且每个按钮都有自己的参数(Test getting Test和Test2得到Test2)但是当我按下按钮时它们都打印"Test2",这意味着它们使用相同的功能和相同的参数.

我怎么解决这个问题?

python lambda loops tkinter button

26
推荐指数
1
解决办法
1万
查看次数

在python的Currying装饰员

我正在尝试在python中写一个currying装饰器,我想我已经有了一般的想法,但仍然有一些不正常的情况......

def curry(fun):

    cache = []
    numargs = fun.func_code.co_argcount

    def new_fun(*args, **kwargs):
        print args
        print kwargs
        cache.extend(list(args))

        if len(cache) >= numargs:   # easier to do it explicitly than with exceptions

            temp = []
            for _ in xrange(numargs):
                temp.append(cache.pop())
            fun(*temp)

    return new_fun


@curry
def myfun(a,b):
    print a,b
Run Code Online (Sandbox Code Playgroud)

虽然对于以下情况,这可以正常工作:

myfun(5)
myfun(5)
Run Code Online (Sandbox Code Playgroud)

对于以下情况,它失败:

myfun(6)(7)
Run Code Online (Sandbox Code Playgroud)

任何有关如何正确执行此操作的指示将非常感谢!

谢谢!

python decorator currying

18
推荐指数
3
解决办法
5981
查看次数

线程在调用Thread.start之前开始运行

t1=threading.Thread(target=self.read())
print "something"
t2=threading.Thread(target=self.runChecks(), args=(self))
Run Code Online (Sandbox Code Playgroud)

self.read无限期地运行,所以程序将无法到达该print行.没有打电话t1.start()怎么可能呢?(即使我打电话给它,它会开始运行并继续下一行,不应该吗?)

python multithreading python-multithreading

17
推荐指数
1
解决办法
3066
查看次数

在Python中使用字典作为switch语句

我正在尝试使用字典在Python中创建一个简单的计算器.这是我的代码:

def default():
    print "Incorrect input!"

def add(a, b):
    print a+b

def sub(a, b):
    print a-b

def mult(a, b):
    print a*b

def div(a, b):
    print a/b

line = raw_input("Input: ")
parts = line.split(" ")
part1 = float(parts[0])
op = parts[1];
part3 = float(parts[2])

dict = {
    '+': add(part1, part3),
    '-': sub(part1, part3),
    '*': mult(part1, part3),
    '/': div(part1, part3)
    }

try:
    dict[op]
except KeyError:
    default()
Run Code Online (Sandbox Code Playgroud)

但所有功能都被激活了.有什么问题?

python dictionary

17
推荐指数
2
解决办法
2万
查看次数

将参数传递给回调函数

def parse(self, response):
    for sel in response.xpath('//tbody/tr'):
        item = HeroItem()
        item['hclass'] = response.request.url.split("/")[8].split('-')[-1]
        item['server'] = response.request.url.split('/')[2].split('.')[0]
        item['hardcore'] = len(response.request.url.split("/")[8].split('-')) == 3
        item['seasonal'] = response.request.url.split("/")[6] == 'season'
        item['rank'] = sel.xpath('td[@class="cell-Rank"]/text()').extract()[0].strip()
        item['battle_tag'] = sel.xpath('td[@class="cell-BattleTag"]//a/text()').extract()[1].strip()
        item['grift'] = sel.xpath('td[@class="cell-RiftLevel"]/text()').extract()[0].strip()
        item['time'] = sel.xpath('td[@class="cell-RiftTime"]/text()').extract()[0].strip()
        item['date'] = sel.xpath('td[@class="cell-RiftTime"]/text()').extract()[0].strip()
        url = 'https://' + item['server'] + '.battle.net/' + sel.xpath('td[@class="cell-BattleTag"]//a/@href').extract()[0].strip()

        yield Request(url, callback=self.parse_profile)

def parse_profile(self, response):
    sel = Selector(response)
    item = HeroItem()
    item['weapon'] = sel.xpath('//li[@class="slot-mainHand"]/a[@class="slot-link"]/@href').extract()[0].split('/')[4]
    return item
Run Code Online (Sandbox Code Playgroud)

好吧,我正在主解析方法中抓取整个表格,我从该表中取了几个字段.其中一个字段是一个网址,我想探索它以获得一大堆字段.如何将已创建的ITEM对象传递给回调函数,以便最终项保留所有字段?

正如上面的代码中所示,我能够保存url中的字段(目前的代码)或只保存表中的字段(只是写yield item)但我不能只生成一个包含所有字段的对象一起.

我试过这个,但很明显,它不起作用.

yield Request(url, callback=self.parse_profile(item))

def parse_profile(self, response, item): …
Run Code Online (Sandbox Code Playgroud)

python arguments callback scrapy

15
推荐指数
2
解决办法
1万
查看次数

如何返回使用变量值的函数?

我想编写一个返回函数列表的函数.作为一个MWE,这是我的函数尝试,它给出了三个函数,它们将0,1和2添加到输入数字:

def foo():
    result = []
    for i in range(3):
        temp = lambda x: x + i
        print(temp(42))  # prints 42, 43, 44
        result.append(temp)
    return result

for f in foo():
    print(f(42))  #prints 44, 44, 44
Run Code Online (Sandbox Code Playgroud)

与我的期望相反,每个函数最终使用i的最后一个值.当我将一个列表用作函数的参数但Python实际上使用指向列表的指针时,我经历过类似的行为,但这里是一个整数,所以我不明白这里发生了什么.我正在运行Python 3.5.

python python-3.x

13
推荐指数
1
解决办法
480
查看次数

如何将函数和参数放入python队列?

我有一个包含2个线程的python程序(让我们将它们命名为'source'和'destination').源线程有时会使用一些参数将消息发布到目标线程.比目标线程选择一条消息,它必须使用保存在消息中的历史记录调用相应的函数.

这个任务可以通过多种方式解决.容易的是在目标线程的消息选择周期中调整一个大的'if ... if..if'并根据收到的消息类型和保存的参数调用函数.但这将导致巨大的代码(或大查找表),并且添加新的消息/处理函数将演变为在消息选择周期中编写代码的额外步骤.

由于python将函数视为第一类对象并具有元组,因此我想在消息中放置函数和参数,因此,目标线程选择一条消息,它只是调用保存在消息中的函数,而不知道它是什么函数.

我可以为具有指定数量的参数的函数编写代码:

from Queue import *
from thread import *
from time import *

q = Queue()

def HandleMsg( arg1, arg2 ) :
  print arg1, arg2

def HandleAnotherMsg( arg1, arg2, arg3 ) :
  print arg1, arg2, arg3

def DestinationThread( a ) :
  while True :
    (f, a, b) = q.get()
    f( a, b )

start_new_thread( DestinationThread, ( 0, ) )
print "start"
sleep( 1 )
q.put( (HandleMsg, 1, 2) )
sleep( 1 )
print "stop"
Run Code Online (Sandbox Code Playgroud)

问题是:如何修改代码,以便我可以把()一个函数与队列中的任意数量的参数放在一起?例如HandleAnotherMsg()?使用q.put((HandleAnotherMsg,1,2,3))会出现编译错误:(

python multithreading

12
推荐指数
3
解决办法
1万
查看次数

我收到类型错误。我如何解决它?

我经常从我的 Python 代码中得到未捕获的异常(错误),这些异常被描述为TypeErrors. 经过大量的实验和研究,我收集了以下示例(以及细微的变化):

TypeError: func() takes 0 positional arguments but 1 was given
TypeError: func() takes from 1 to 2 positional arguments but 3 were given
TypeError: func() got an unexpected keyword argument 'arg'
TypeError: func() missing 1 required positional argument: 'arg'
TypeError: func() missing 1 required keyword-only argument: 'arg'
TypeError: func() got multiple values for argument 'arg'
TypeError: MyClass() takes no arguments
TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: can only concatenate str …
Run Code Online (Sandbox Code Playgroud)

python debugging typeerror

11
推荐指数
2
解决办法
8049
查看次数