문자열에 이름이있는 속성을 만드는 방법은 무엇입니까?
-
06-07-2019 - |
문제
Python을 사용하면 클래스에서 속성을 만들고 싶지만 문자열로 이름을 갖습니다. 일반적으로 당신은 다음과 같습니다.
blah = property(get_blah, set_blah, del_blah, "bleh blih")
여기서 get_, set_ 및 del_blah가 그에 따라 정의되었습니다. 나는 다음과 같은 변수의 속성 이름으로 똑같이하려고 노력했습니다.
setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih"))
그러나 그것은 작동하지 않습니다. 첫 번째 사례 Blah는 재산의 가치를 반환합니다. 두 번째 경우에는 재산을 반환합니다. <property object at 0xbb1aa0>
. 작동하도록 어떻게 정의해야합니까?
해결책
내가 말하는 것처럼, 차이점은 첫 번째 버전에서 클래스 속성을 속성 결과로 변경하고 인스턴스에서 설정 한 두 번째 속성을 변경한다는 것입니다 (다른!).
이 버전은 어떻습니까 :
setattr(MyClass, "blah", property(self.get_blah, self.set_blah,
self.del_blah, "bleh blih"))
당신은 또한 이것을 할 수 있습니다 :
setattr(type(self), "blah", property(self.get_blah, self.set_blah,
self.del_blah, "bleh blih"))
다른 팁
한 가지 방법은 Locals ()에 글을 쓰는 것입니다.
class X:
for attr in ["a","b","c"]:
def getter(self, name=attr):
return name+"_value"
locals()[attr] = property(getter, None, None, attr)
x = X()
print x.a
print x.b
print x.c
주어진
a_value
b_value
c_value
당신이하려는 일을 이해한다면, 당신은 수업을 무시함으로써 그것을 달성 할 수 있습니다. getattr 그리고 setattr 행동 양식.
예를 들어:
class Something(object):
def __getattr__(self, name):
# The name of the property retrieved is a string called name
return "You're getting %s" % name
something = Something()
print something.foo
print something.bar
인쇄 :
You're getting foo
You're getting bar
이런 식으로 당신은 문자열에 속성의 이름을 가진 일반적인 getter와 setter를 가질 수 있고 그에 따라 무언가를 할 수 있습니다.
제휴하지 않습니다 StackOverflow