質問

いがある場合は内蔵機能を辞書から任意のオブジェクト?思うようになります:

>>> class Foo:
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }

注意: でを含めないでください。だけます。

役に立ちましたか?

解決

このベストプラクティスのPython2.7利用 新スタイル 授業では、Python3)、

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 電話を通じて、セットの辞書名またを設定した例えば:

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__.

このヒント属性がオブジェクトを継承できます。例えば、

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

hasattr、'x')がtrueであるが、'x'で表示されません。__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__.

これまでの完全クラス+インスタンス辞書です。現在残ったのはに対して繰り返し処理を実行すると収量に戻ります。

また、プランを利用するにあたり多くを作成することができ @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))

遅めの答えが提供のための完全性、利益のgooglers:

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

この表示を行ないませんで定義されているメソッドのクラスは、そのショー分野に割り当てlambdas以外で始まりダブルアンダースコア.

と思う最も簡単な方法を getitem 属性のためのクラスです。場合を記述する必要がありますのオブジェクトを作成できるカスタム setattr .ここでは例 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'}

PYTHON3:

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