임의의 객체에서 사전을 작성하는 내장 함수가 있는지 알고 있습니까? 나는 이런 식으로하고 싶다 :
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
참고 : 방법을 포함해서는 안됩니다. 필드 만.
답변
Python 2.7의 모범 사례는 새로운 스타일 클래스 (Python 3에서는 필요하지 않음)를 사용하는 것입니다.
class Foo(object):
...
또한 ‘객체’와 ‘클래스’에는 차이가 있습니다. 임의의 객체 에서 사전을 만들려면 사용하기에 충분합니다 __dict__
. 일반적으로 클래스 수준에서 메소드를 선언하고 인스턴스 레벨에서 속성을 선언하므로 __dict__
좋을 것입니다. 예를 들면 다음과 같습니다.
>>> class A(object):
... def __init__(self):
... self.b = 1
... self.c = 2
... def do_nothing(self):
... pass
...
>>> a = A()
>>> a.__dict__
{'c': 2, 'b': 1}
더 나은 접근법 ( 로버트 가 주석에서 제안 )은 내장 vars
함수입니다.
>>> vars(a)
{'c': 2, 'b': 1}
또는 원하는 작업에 따라에서 상속하는 것이 좋습니다 dict
. 그런 다음 클래스는 이미 사전이며 원하는 경우 dict을 재정의 getattr
및 / 또는 setattr
호출하고 설정할 수 있습니다 . 예를 들면 다음과 같습니다.
class Foo(dict):
def __init__(self):
pass
def __getattr__(self, attr):
return self[attr]
# etc...
답변
대신에 x.__dict__
, 실제로 사용하기가 더 pythonic vars(x)
입니다.
답변
dir
내장 당신에게 같은 특별한 방법을 포함하는 모든 객체의 속성을 줄 것이다 __str__
, __dict__
당신은 아마 원하지 않는 다른 사람의 전체 무리를. 그러나 다음과 같은 것을 할 수 있습니다.
>>> class Foo(object):
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))
{ 'bar': 'hello', 'baz': 'world' }
따라서 다음 props
과 같이 함수 를 정의하여 메소드가 아닌 데이터 속성 만 리턴하도록이를 확장 할 수 있습니다 .
import inspect
def props(obj):
pr = {}
for name in dir(obj):
value = getattr(obj, name)
if not name.startswith('__') and not inspect.ismethod(value):
pr[name] = value
return pr
답변
나는 두 답변의 조합으로 정착했습니다.
dict((key, value) for key, value in f.__dict__.iteritems()
if not callable(value) and not key.startswith('__'))
답변
객체를 dict로 변환하는 방법을 보여주기 위해 시간이 걸릴 것이라고 생각했습니다 dict(obj)
.
class A(object):
d = '4'
e = '5'
f = '6'
def __init__(self):
self.a = '1'
self.b = '2'
self.c = '3'
def __iter__(self):
# first start by grabbing the Class items
iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__')
# then update the class items with the instance items
iters.update(self.__dict__)
# now 'yield' through the items
for x,y in iters.items():
yield x,y
a = A()
print(dict(a))
# prints "{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}"
이 코드의 핵심 부분은 __iter__
함수입니다.
의견에서 알 수 있듯이 가장 먼저 할 일은 Class 항목을 잡고 ‘__’으로 시작하는 것을 막는 것입니다.
일단 생성 한 후에 dict
는 update
dict 함수를 사용 하여 인스턴스를 전달할 수 있습니다 __dict__
.
이들은 당신에게 회원의 완전한 클래스 + 인스턴스 사전을 제공합니다. 이제 남은 것은 그것들을 반복하고 수익을 얻는 것입니다.
또한 이것을 많이 사용할 계획이라면 @iterable
클래스 데코레이터를 만들 수 있습니다 .
def iterable(cls):
def iterfn(self):
iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != '__')
iters.update(self.__dict__)
for x,y in iters.items():
yield x,y
cls.__iter__ = iterfn
return cls
@iterable
class B(object):
d = 'd'
e = 'e'
f = 'f'
def __init__(self):
self.a = 'a'
self.b = 'b'
self.c = 'c'
b = B()
print(dict(b))
답변
임의의 객체 에서 사전을 만들려면 사용하기에 충분합니다
__dict__
.
객체가 클래스에서 상속하는 속성이 누락되었습니다. 예를 들어
class c(object):
x = 3
a = c()
hasattr (a, ‘x’)는 true이지만 ‘x’는 a .__ dict__에 나타나지 않습니다.
답변
답변은 늦었지만 Google 직원의 완전성과 이점을 제공했습니다.
def props(x):
return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))
클래스에 정의 된 메소드는 표시되지 않지만 람다에 할당 된 필드 나 이중 밑줄로 시작하는 필드를 포함하는 필드가 계속 표시됩니다.
