在python 27 如何使用**kwargs 来定义class 中的成员变量?
In python 27 how do I use **kwargs to define member variables in a class?
我希望在 Python27 中使用 ** 定义对象 class 的成员变量,但是当我 运行 下面的代码不起作用时。
class Object:
def __init__(self, *args, **kwargs):
for k, v in kwargs.iteritems():
self.k = v
print str(k) + " " + str(v) + " " + str(self.k)
print str(self.x)
print str(self.y)
print self.name
Player = Object(x=10, y=10, name="Player")
我很清楚问题出在哪里,因为当我打电话给
print str(self.k)
它打印循环中的最后一个条目。所以我很确定发生的事情是,当 k 是键 'name' 并且 v 是值 "Player" 时,它正在将 "Player" 分配给新成员变量 'self.k' 而不是 'self.name' 但我不知道该怎么办。
要设置名称仅在运行时已知的成员变量,您应该使用 setattr()
内置函数。
setattr(object, name, value)
This is the counterpart of getattr()
. The
arguments are an object, a string and an arbitrary value. The string
may name an existing attribute or a new attribute. The function
assigns the value to the attribute, provided the object allows it. For
example, setattr(x, 'foobar', 123)
is equivalent to x.foobar = 123
.
你的情况:
for k, v in kwargs.iteritems():
setattr(self, k, v)
我希望在 Python27 中使用 ** 定义对象 class 的成员变量,但是当我 运行 下面的代码不起作用时。
class Object:
def __init__(self, *args, **kwargs):
for k, v in kwargs.iteritems():
self.k = v
print str(k) + " " + str(v) + " " + str(self.k)
print str(self.x)
print str(self.y)
print self.name
Player = Object(x=10, y=10, name="Player")
我很清楚问题出在哪里,因为当我打电话给
print str(self.k)
它打印循环中的最后一个条目。所以我很确定发生的事情是,当 k 是键 'name' 并且 v 是值 "Player" 时,它正在将 "Player" 分配给新成员变量 'self.k' 而不是 'self.name' 但我不知道该怎么办。
要设置名称仅在运行时已知的成员变量,您应该使用 setattr()
内置函数。
setattr(object, name, value)
This is the counterpart of
getattr()
. The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example,setattr(x, 'foobar', 123)
is equivalent tox.foobar = 123
.
你的情况:
for k, v in kwargs.iteritems():
setattr(self, k, v)