파이썬에서 setattr () 사용
나는 사용하는 것이 아니라 사용 방법의 기본을 설명 할 사람을 찾고 있습니다 setattr()
.
내 문제는 하나의 클래스 메서드 / 함수를 사용하여 데이터를 반환 한 다음 다른 메서드 / 함수에 넣을 때 발생했습니다. 이 경우에는 더 간단한 접근 방식이 훨씬 더 좋을 수 있지만 클래스가 작동 / 사용되는 방식을 이해하려고합니다. 이 문제는에 달려있는 것처럼 보이며 이것은 setattr()
이것을 매우 간단하게 사용하려는 시도입니다.
꽤 같은 문제가되지 않습니다 만, 나는 다음과 같은 한 파이썬 하드 방법을 ex42 년 - while
루프 @ 선 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 thanks for your help.
I think I can now explain my own answer! This required a better grasp of self as an object for me. It's an instance name that gets tagged up with stuff like attributes.
The class could be a Town, and then. getattr
looks for a house using it's name so you are ready to call on it soon, and comes up with a different place if you don't find the house --With getattr
a 'name' exists, and you go find it. Makes the step from one function to another dynamic As a bonus you may have a default value, useful to get a fallback default method--connection failed or something?
setattr
builds a house and gives it a name so you can call in on it later. You could potentially rebuild this house, or go to a particular place if you are unable to find it. --setattr
makes an attribute name and gives, or changes it's value, to be called on later Perhaps a user turns sound off, then future methods don't output any audio.
I could have written my function a number of ways, but there's no need to change any attributes:
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)
Properly corrected code:
def run_it(self):
value_returned = self.get_thing()
self.use_it(value_returned)
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 tox.foobar = 123
.
If this isn't enough, explain what you don't understand.
Setattr: 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.
ReferenceURL : https://stackoverflow.com/questions/9561174/using-setattr-in-python
'development' 카테고리의 다른 글
detailTextLabel이 보이지 않는 이유는 무엇입니까? (0) | 2021.01.09 |
---|---|
Rails의 URL에서 쿼리 문자열을 얻는 방법 (0) | 2021.01.09 |
출력을 변수로 업데이트 (0) | 2021.01.09 |
Pandas Merge-열 중복을 방지하는 방법 (0) | 2021.01.09 |
Android Studio의 xcrun 개발자 경로 변경 (0) | 2021.01.09 |