我需要一个行为类似字符串的类,但也需要额外的类kwargs.因此我子类str:
class Child(str):
def __init__(self, x, **kwargs):
# some code ...
pass
inst = Child('a', y=2)
print(inst)
Run Code Online (Sandbox Code Playgroud)
然而这引起了:
Traceback (most recent call last):
File "/home/user1/Project/exp1.py", line 8, in <module>
inst = Child('a', y=2)
TypeError: 'y' is an invalid keyword argument for this function
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为下面的代码没有任何错误:
class Child(object):
def __init__(self, x, **kwargs):
# some code ...
pass
inst = Child('a', y=2)
Run Code Online (Sandbox Code Playgroud)
问题:
str,int,float,tuple相比其他类,如等object,list,dict等?我基本上想要扩展当前范围,就像调用函数时的字典一样.
我记得在某个地方看到过这个,但我不记得在哪里或怎么做.
这是一个简单的例子
def bar(a, b, c, d, e, f):
pass
def foo(a, b, c, d, e, f):
# Instead of doing this
bar(a, b, c, d, e, f)
# or
bar(a=a, b=b, c=c, d=d, e=e, f=f)
# I'd like to do this
bar(**local_scope)
Run Code Online (Sandbox Code Playgroud)
我想象的事情还是可以做到的?
我想知道在执行查询时何时触摸db。更准确地说,何时执行查询:
我有这个kwargs dic:
kwargs = {'name__startswith':'somename','color__iexact':'somecolor'}
Run Code Online (Sandbox Code Playgroud)
但仅用于name__startswith查询,我需要distinct()。而不是color__iexact。
我想,我会为设定name__startswith的distinct()在这样的循环:
for q in kwargs:
if q == 'name__startswith':
Thing.objects.filter(name__startswith=somename).distinct('id')
Run Code Online (Sandbox Code Playgroud)
然后动态查询所有内容:
allthings = Thing.objects.filter(**kwargs)
Run Code Online (Sandbox Code Playgroud)
但这是不对的,我似乎在这里做两件事。
我如何动态地执行这两个查询?
我有一个函数,它将数据放入数据库,称为new_item():
def new_item(self, item, **optional):
Run Code Online (Sandbox Code Playgroud)
发送Web表单后,函数应检查用户输入,然后使用此函数将用户输入放入数据库(我使用Flask,函数名称为add_item()):
Market.new_item([request.form['title'],
session.get('user_id'),
request.form['category']],
{'desc': request.form['desc'],
'place': request.form['place'],
'price': request.form['price'],
'ono': ono})
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
File X, line 99, in add_item
'ono': ono})
TypeError: new_item() takes exactly 2 arguments (3 given)
Run Code Online (Sandbox Code Playgroud)
毛发调试我在调用函数之前打印此语句add_item.控制台输出是:
([u'iPhone 5', '791465667539154', u'2'],
{'price': u'99', 'place': u'Bossental', 'ono': True, 'desc': u'My brand new iPhone'})
Run Code Online (Sandbox Code Playgroud)
我真的不知道出了什么问题.我以前从未和之合作**kwargs过; 这与问题有关吗?
考虑以下:
def my_wrapper(wrapper_argument=False, *args, **kwargs):
return my_function(*args, **kwargs)
def my_function(arg1, arg2, params=None):
# do_stuff
return result
Run Code Online (Sandbox Code Playgroud)
当我打电话给上面的时候:
my_wrapper('foo', 'bar', wrapper_argument=True)
Run Code Online (Sandbox Code Playgroud)
我明白了:
TypeError: my_function() got multiple values for argument 'wrapper_argument'
Run Code Online (Sandbox Code Playgroud)
为什么?参数的排序可能是错误的吗?
我有两个类具有相同名称的方法,但此方法使用不同的参数.所以我考虑使用**kwargs(见下面的例子).但是这两种方法中的一种不需要任何参数,所以我得到这个错误:
TypeError:print_smt()占用1个位置参数,但给出了2个
因为我想将空字典传递给函数.
我怎么解决这个问题?我是否被迫使用if语句来调用带有和不带参数的函数,或者有更好的方法来解决问题?
class Bar(object):
def print_smt(self, text):
print(text)
class Foo(object):
def print_smt(self):
print("Nothing")
def test(obj, **p2):
obj.print_smt(p2)
bar = Bar()
test(bar, text='print this')
foo = Foo()
test(foo) # This one breaks!
Run Code Online (Sandbox Code Playgroud) 我想建立一个原型:
def foo(a,t=([0]*len(a))):
print t
Run Code Online (Sandbox Code Playgroud)
由于目前不重要的原因.我传入的是可变长度列表参数.但是,Linux上的Python 2.7.10总是返回如下:
>>> a = [1,2,3,4]
>>> foo(a)
[O, 0]
Run Code Online (Sandbox Code Playgroud)
没有函数调用,这些都不会以意外的方式运行.是什么导致Python总是认为在foo()中的变量赋值期间传递的列表是长度为2?
我正在Python3中学习多重继承。我想知道为什么案例1可以工作,但案例2却不行。这是我的代码段。
class ContactList(list):
def search(self, name):
"""Return all contacts that contain the search value
in their name."""
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList()
def __init__(self, name="", email="", **kwargs):
super().__init__(**kwargs)
self.name = name
self.email = email
Contact.all_contacts.append(self)
print("Cotact")
class AddressHolder:
def __init__(self, street="", city="", state="", code="", **kwargs):
super().__init__(**kwargs)
self.street = street
self.city = city
self.state = state
self.code = code
print("AddressHolder")
class Friend(Contact, AddressHolder):
# case# 1
# …Run Code Online (Sandbox Code Playgroud) make_option(
'--file',
action='store',
dest='in_file',
help="File to process"),
make_option(
'--filter',
action='store',
dest='filter',
help="Filter by a store object")
def run(self, *args, **kwargs):
with open(kwargs['in_file']) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
filter_store = row[0] #123123
update_store = row[1]
Store.objects.filter(**kwargs['filter'] = filter_store).update(**kwargs['update'] = update_store)
Run Code Online (Sandbox Code Playgroud)
这不包括完整的代码^
我试图用存储ID过滤数据库我通过存储的kwargs传递,但得到语法错误.
Store.objects.filter(**kwargs['filter'] = filter_store)
Run Code Online (Sandbox Code Playgroud)
基本上**kwargs['filter']这里有"id"值并且filter_store有商店ID.它应该执行以下操作**kwargs:
Store.objects.filter(id = 4334225)
Run Code Online (Sandbox Code Playgroud) 我在装饰器库中遇到了一个非常奇怪的行为,在下一个代码中对此进行了解释:
from decorator import decorator
@decorator
def wrap(f, a, *args, **kwargs):
print 'Decorator:', a, args, kwargs
return f(a, *args, **kwargs)
def mywrap(f):
def new_f(a, *args, **kwargs):
print 'Home made decorator:', a, args, kwargs
return f(a, *args, **kwargs)
return new_f
@wrap
def funcion(a, b, *args, **kwargs):
pass
@mywrap
def myfuncion(a, b, *args, **kwargs):
pass
funcion(1, b=2)
myfuncion(1, b=2)
Run Code Online (Sandbox Code Playgroud)
执行此脚本打印:
$ python /tmp/test.py
Decorator: 1 (2,) {}
Home made decorator: 1 () {'b': 2}
Run Code Online (Sandbox Code Playgroud)
'decorator'隐藏了args中的kwargs,如何在不使用"自制"装饰器的情况下解决这个问题.
谢谢.
kwargs ×10
python ×9
python-3.x ×3
django ×2
decorator ×1
filter ×1
flask ×1
object ×1
parent-child ×1
python-2.7 ×1
subclass ×1
typeerror ×1