有什么方法可以在不创建类实例的情况下获取类实例的属性? [英] Is there any way to get class instance attributes without creating class instance?

查看:153
本文介绍了有什么方法可以在不创建类实例的情况下获取类实例的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一个问题的链接:从字典创建类实例吗?
因此,我试图从词典创建类实例,该实例包含该类没有的键.例如:

Here is the link to my first question: Creating class instance from dictionary?
So I am trying to create class instance from dictionary which holds keys that class has not. For example:

class MyClass(object):
    def __init__(self, value1, value2):
        self.attr1 = value1
        self.attr2 = value2

dict = {'attr1': 'value1', 'attr2': 'value2', 'redundant_key': 'value3'}

在创建类实例之前,我必须从字典中删除此redundant_key

Before creating class instance I have to delete this redundant_key from dict

dict.pop('redundant_key', None)
new_instance = MyClass(**dict)

问题是我有几个类和带有很多键的字典(我有几个json格式的响应,表示为dicts,我想从这个json响应中创建对象).我已经从前面的问题中找到了一个临时解决方案-如何删除冗余密钥.我只能使用需要的键从旧字典创建新字典:

The problem is that I have several classes and several dicts with a lot of keys (I have several responses in json format which are represented as dicts and I want to create objects from this json responses). I already found an interim solution from previous question - how to delete redundant keys. I can create new dict from old dict only with keys that I need:

new_dict = {key: old_dict[key] for key in allowed_keys}

下面是代码:

class MyClass(object):
    def __init__(self, value1, value2):
        self.attr1 = value1
        self.attr2 = value2

dict = {'attr1': 'value1', 'attr2': 'value2', 'redundant_key': 'value3'}
new_instance = MyClass(**{key: dict[key] for key in allowed_keys})

我现在所要做的就是获取allowed_keys.那么问题来了-有什么方法可以在不创建类实例的情况下获取类实例的属性?

All I need now is to get allowed_keys. So the question - Is there any way to get class instance attributes without creating class instance?

推荐答案

如果您坚持使用过于通用的字典来初始化对象,只需定义

If you insist on using an overly general dictionary to initialize your object, just define __init__ to accept, but ignore, the extra keys.

class MyClass(object):
    def __init__(self, attr1, attr2, **kwargs):
        self.attr1 = attr1
        self.attr2 = attr2

d = {'attr1': 'value1', 'attr2': 'value2', 'extra_key': 'value3'}
new_instance = MyClass(**d)

如果您无法修改 __init__ (如果它是从SQLAlchemy声明性基类继承的,则似乎是这种情况),添加一个替代构造函数以接受所有关键字参数,但挑选所需的参数.

If you can't modify __init__ (as appears to be the case if it inherits from a SQLAlchemy declarative base), add an alternate constructor to accept all the keyword arguments but pick out the ones you need.

class MyClass(Base):
    @classmethod
    def from_dict(cls, **kwargs):
        # Let any KeyErrors propagate back to the caller.
        # They're the one who forgot to make sure **kwargs
        # contained the right keys.
        value1 = kwargs['attr1']
        value2 = kwargs['attr2']
        return cls(value1, value2)

new_instance = MyClass.from_dict(**d)

这篇关于有什么方法可以在不创建类实例的情况下获取类实例的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆