在 python 中使用 setattr()

我正在寻找一个人来解释如何使用的基本知识,而不是使用 setattr()

我的问题出现在试图使用一个类方法/函数来返回数据,然后将这些数据放入另一个方法/函数中。在这种情况下,一种更简单的方法可能会更好,但是我试图理解类是如何工作/使用的。这个问题似乎取决于 setattr(),这是我尝试使用它的一个相当简单的方法。

虽然这不是完全相同的问题,但我遵循 巨蟒之路,第42集 & mash; 的 while循环@line 18-41。

我尝试编写一个 \__init__()代替使用 getattr(),认为可能需要在类的名称空间中包含一些内容,但这似乎没有帮助。

#! /bin/python2.6


class HolyGrail(object):


def __init__(self):
self.start = 'start_at_init'


# function definition in question:
# TypeError: 'str' object is not callable


def run_it(self):
start = setattr(self, 'name', 'get_thing')
start = self.name


# Something wrong here?
value_returned = start() #I believe this == self.get_thing()
use_it(value_returned)


"""
# alternate function definitions
# NameError: global name 'start' is not defined


def __init__(self):
self.start = 'get_thing'


def run_it(self):
go_do_it = getattr(self, start)
first_output = go_do_it()
use_it(first_output)
"""


def get_thing(self):
return "The Knights Who Say ... Ni!"


def use_it(self, x):
print x
print "We want a shrubbery!"


my_instance = HolyGrail()
my_instance.run_it()

@ Karl Knechtel@Amber@Chris Morgan 谢谢你的帮助。

我想我现在可以解释我自己的答案了!对我来说,这需要更好地把握自我作为一个对象。它是一个实例名,用属性之类的东西进行标记。

班级可以是一个城镇,然后。 getattr寻找一个房子使用它的名字,所以你准备呼吁它很快,并提出了一个不同的地方,如果你没有找到房子 --使用 getattr存在一个“名称”,并且您可以找到它 作为奖励,你可能有一个默认值,有用得到一个回退默认方法-连接失败或什么?

setattr建造了一座房子,并给它起了一个名字,这样你以后就可以拜访它了。 你可以重建这所房子,或者去一个特定的地方,如果你无法找到它。 —— setattr创建一个属性名,并给出或更改它的值,以供稍后调用 也许用户关闭了声音,那么未来的方法不会输出任何音频。

我可以通过多种方式编写函数,但是不需要更改任何属性:

def run_it(self):
yo = getattr(self, 'get_thing')
answer = yo()
setattr(self, 'deal_accepted', self.use_it) #really ott
no = getattr(self, 'deal_accepted')
no(answer)

正确修改代码:

def run_it(self):
value_returned = self.get_thing()
self.use_it(value_returned)
198901 次浏览

You are setting self.name to the string "get_thing", not the function get_thing.

If you want self.name to be a function, then you should set it to one:

setattr(self, 'name', self.get_thing)

However, that's completely unnecessary for your other code, because you could just call it directly:

value_returned = self.get_thing()

The Python docs say all that needs to be said, as far as I can see.

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.

We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value. and with getattr we retrive these values

For example

Employee = type("Employee", (object,), dict())


employee = Employee()


# Set salary to 1000
setattr(employee,"salary", 1000 )


# Get the Salary
value = getattr(employee, "salary")


print(value)

Suppose you want to give attributes to an instance which was previously not written in code. The setattr() does just that. It takes the instance of the class self and key and value to set.

class Example:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)

To add to the other answers, a common use case I have found for setattr() is when using configs. It is common to parse configs from a file (.ini file or whatever) into a dictionary. So you end up with something like:

configs = {'memory': 2.5, 'colour': 'red', 'charge': 0, ... }

If you want to then assign these configs to a class to be stored and passed around, you could do simple assignment:

MyClass.memory = configs['memory']
MyClass.colour = configs['colour']
MyClass.charge = configs['charge']
...

However, it is much easier and less verbose to loop over the configs, and setattr() like so:

for name, val in configs.items():
setattr(MyClass, name, val)

As long as your dictionary keys have the proper names, this works very well and is nice and tidy.

*Note, the dict keys need to be strings as they will be the class object names.

The first thing that strikes me about your code is that you set start to the value of setattr.

start = setattr(self, 'name', 'get_thing')
start = self.name


# Something wrong here?
value_returned = start() #I believe this == self.get_thing()
use_it(value_returned)

The return value of setattr is None. It is an operation that is performed and does a task, but does not return a value. Similar to calling something like exit(), the operation just runs. Enter python from your shell and you'll see

a = exit() #exits your program

Setting a to print('x') performs like exit and like your setattr, however, calling upon a doesn't invoke our method.

a = print('15') #returns 15
a #returns None

if you want to be able to call upon setattr from within your class, you could define a method for it.

def setAtrrClassInstance(self,name,value):  #This returns None
setattr(self,name,value)