문제

임의의 객체로부터 사전을 구축하는 내장 함수가 있는지 알고 계십니까?나는 다음과 같은 것을하고 싶습니다 :

>>> 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.그럼 네 수업은 이미 사전, 원하는 경우 재정의할 수 있습니다. getattr 및/또는 setattr 전화를 걸어 dict를 설정합니다.예를 들어:

class Foo(dict):
    def __init__(self):
        pass
    def __getattr__(self, attr):
        return self[attr]

    # etc...

다른 팁

대신에 x.__dict__, 실제로 사용하는 것이 더 파이썬적입니다. 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__.

이로 인해 객체가 해당 클래스에서 상속받은 속성이 누락됩니다.예를 들어,

class c(object):
    x = 3
a = c()

hasattr(a, 'x')는 true이지만 'x'는 a.__dict__에 나타나지 않습니다.

나는 객체를 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__ 기능.

설명에 설명되어 있듯이, 우리가 가장 먼저 하는 일은 클래스 항목을 잡고 '__'로 시작하는 항목을 방지하는 것입니다.

일단 그것을 만들고 나면 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))

답변이 늦었지만 완전성과 Google 직원의 이익을 위해 제공되었습니다.

def props(x):
    return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))

클래스에 정의된 메서드는 표시되지 않지만 람다에 할당된 필드나 이중 밑줄로 시작하는 필드를 포함하는 필드는 계속 표시됩니다.

내 생각에 가장 쉬운 방법은 getitem 클래스에 대한 속성입니다.객체에 써야 하는 경우 사용자 정의를 생성할 수 있습니다. 설정 .여기에 대한 예가 있습니다. getitem:

class A(object):
    def __init__(self):
        self.b = 1
        self.c = 2
    def __getitem__(self, item):
        return self.__dict__[item]

# Usage: 
a = A()
a.__getitem__('b')  # Outputs 1
a.__dict__  # Outputs {'c': 2, 'b': 1}
vars(a)  # Outputs {'c': 2, 'b': 1}

딕셔너리 객체 속성을 사전에 생성하고 사전 객체를 사용하여 필요한 항목을 얻을 수 있습니다.

속성의 일부를 나열하려면 재정의하십시오. __dict__:

def __dict__(self):
    d = {
    'attr_1' : self.attr_1,
    ...
    }
    return d

# Call __dict__
d = instance.__dict__()

이것은 많은 도움이 됩니다. instance 대규모 블록 데이터를 얻고 푸시하고 싶습니다. d 메시지 대기열과 같은 Redis에.

사용의 단점 __dict__ 그것은 얕다는 것입니다.하위 클래스를 사전으로 변환하지 않습니다.

Python3.5 이상을 사용하는 경우 다음을 사용할 수 있습니다. jsons:

>>> import jsons
>>> jsons.dump(f)
{'bar': 'hello', 'baz': 'world'}

파이썬 3:

class DateTimeDecoder(json.JSONDecoder):

   def __init__(self, *args, **kargs):
        JSONDecoder.__init__(self, object_hook=self.dict_to_object,
                         *args, **kargs)

   def dict_to_object(self, d):
       if '__type__' not in d:
          return d

       type = d.pop('__type__')
       try:
          dateobj = datetime(**d)
          return dateobj
       except:
          d['__type__'] = type
          return d

def json_default_format(value):
    try:
        if isinstance(value, datetime):
            return {
                '__type__': 'datetime',
                'year': value.year,
                'month': value.month,
                'day': value.day,
                'hour': value.hour,
                'minute': value.minute,
                'second': value.second,
                'microsecond': value.microsecond,
            }
        if isinstance(value, decimal.Decimal):
            return float(value)
        if isinstance(value, Enum):
            return value.name
        else:
            return vars(value)
    except Exception as e:
        raise ValueError

이제 자신의 클래스 내에서 위 코드를 사용할 수 있습니다.

class Foo():
  def toJSON(self):
        return json.loads(
            json.dumps(self, sort_keys=True, indent=4, separators=(',', ': '), default=json_default_format), cls=DateTimeDecoder)


Foo().toJSON() 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top