Python 3.2.3.这里列出了一些有关常规变量的想法,但似乎**kwargs按照不同的规则进行播放...所以为什么这不起作用?如何查看**kwargs中的密钥是否存在?
if kwargs['errormessage']:
print("It exists")
Run Code Online (Sandbox Code Playgroud)
我也认为这应该有效,但事实并非如此 -
if errormessage in kwargs:
print("yeah it's here")
Run Code Online (Sandbox Code Playgroud)
我猜是因为kwargs是可迭代的?我是否必须遍历它才能检查特定键是否存在?
我经常发现自己覆盖了父类的方法,并且永远无法决定是否应该明确地列出给定的参数,或者只是使用一个毯子*args, **kwargs结构.一个版本比另一个好吗?有最好的做法吗?我缺少什么(dis-)优势?
class Parent(object):
def save(self, commit=True):
# ...
class Explicit(Parent):
def save(self, commit=True):
super(Explicit, self).save(commit=commit)
# more logic
class Blanket(Parent):
def save(self, *args, **kwargs):
super(Blanket, self).save(*args, **kwargs)
# more logic
Run Code Online (Sandbox Code Playgroud)
显性变体的感知益处
毯子变体的感知好处
一个flash问题,我正在看下面的代码
from __future__ import division
import math
import time
def dft(x, inverse = False, verbose = False) :
t = time.clock()
N = len(x)
inv = -1 if not inverse else 1
X =[0] * N
for k in xrange(N) :
for n in xrange(N) :
X[k] += x[n] * math.e**(inv * 2j * math.pi * k * n / N)
if inverse :
X[k] /= N
t = time.clock() - t
if verbose :
print "Computed","an inverse" if inverse …Run Code Online (Sandbox Code Playgroud) 我正在阅读mercurial的源代码,并在commands.py中找到了这样的函数def:
def import_(ui, repo, patch1=None, *patches, **opts):
...
Run Code Online (Sandbox Code Playgroud)
在python中,postional args必须放在关键字args之前.但这里patch1是一个关键字参数,后跟一个位置参数*patches.为什么这样好?
Python中的构造函数通常如下所示:
class SomeClass:
def __init__(self, a, b = None, c = defC):
self.a = a
self.b = b or []
self.c = c
Run Code Online (Sandbox Code Playgroud)
有没有这样的快捷方式,例如简单地定义__init__(self,**kwargs)和使用键作为属性self?
在 Python 3.x 中,我想为特定的已知函数proxiedFunc创建一个代理函数_proxy并保证传递的所有参数都完全“转发”,就像它们直接传递给proxiedFunc 一样。
# Pseudo-Python code
def _proxy(???generic_parameters???):
return proxiedFunc(???arguments???)
Run Code Online (Sandbox Code Playgroud)
我所说的“纯直通”是什么意思 -> _proxy方法的实现不应受到对proxiedMethod的(非)兼容更改的影响,假设函数名称不变(SOLID 原则)。显然,呼叫者_proxy需要,如果要修改proxiedMethod是不兼容的改变(即我不打算对_proxy是一个适配器,但是这将是一个可能性)。
新的python.现在无法找出这个问题的答案2天..会感激一些帮助,谷歌搜索没有帮助.
填写"foo"和"bar"函数,以便它们可以接收可变数量的参数(3或更多)"foo"函数必须返回所接收的额外参数的数量.如果带有关键字"magicnumber"的参数值为7,则"bar"必须返回"True",否则返回False.
# edit the functions prototype and implementation
def foo(a, b, c):
pass
def bar(a, b, c):
pass
# test code
if foo(1,2,3,4) == 1:
print "Good."
if foo(1,2,3,4,5) == 2:
print "Better."
if bar(1,2,3,magicnumber = 6) == False:
print "Great."
if bar(1,2,3,magicnumber = 7) == True:
print "Awesome!"
Run Code Online (Sandbox Code Playgroud)
我猜..一些部分代码会很好,无法理解**kwargs以及所有这些:
使用关键字参数,您不能只引用字典中的潜在关键字值,因为它们可能不存在。引用可能存在或不存在的关键字值的最佳方法是什么?我发现自己在做这样的事情:
def save_link(link, user, **kwargs):
if "auto" in kwargs:
auto = kwargs["auto"]
else:
auto = False
Run Code Online (Sandbox Code Playgroud)
为了提供默认值并创建可靠存在的变量。有没有更好的办法?
python ×8
python-3.x ×2
class ×1
constructor ×1
dictionary ×1
func ×1
function ×1
inheritance ×1
kwargs ×1
math ×1
python-2.7 ×1