简体   繁体   English

Python Class 属性表现为字典

[英]Python Class property behave as Dictionary

I have a very simple class that defines properties like:我有一个非常简单的 class 定义如下属性:

class Person:
    fields = set()

    @property
    def id(self):
        self.fields.add('id')
        return 'person.id'

The idea is for this class to record which properties have been accessed.这个想法是让这个 class 记录已访问的属性。 Now the problem comes when I need to start supporting: person.metadata.key where metadata is basically an HStore object or 1 level JSON, the key is arbitrary and the idea is for the class Person so record access to any of the keys in metadata .现在问题来了,当我需要开始支持时: person.metadata.key ,其中元数据基本上是 HStore object 或 1 级 JSON,密钥是任意的,想法是针对metadata中的 ZA2F2ED4F8EBC2CBB4C21A29DZ1 对 Person 记录的任何密钥的访问. I tried something like this:我试过这样的事情:

class CustomerBulkContext:

    fields = set()

    class PersonMetadata:
        def __getitem__(self, attr):
            fields.add(f'metadata.{attr}')
            return f'person.metadata.{attr}'

    metadata = CustomerMetadataContext()

Now obviously the problem is that fields inside PersonMetadata is not a known variable at this point.现在显然问题是 PersonMetadata 中的fields此时不是已知变量。 How can I overcome this issue, I don't know if it's possible to do in Python without too much code.我该如何克服这个问题,我不知道是否可以在没有太多代码的情况下在 Python 中完成。

In order to track accesses like person.metadata.key you'd have to have person.metadata return an object which itself tracks how it was accessed.为了跟踪像person.metadata.key这样的访问,你必须让person.metadata返回一个 object ,它本身会跟踪它是如何被访问的。 In order to track the whole chain, you'd pass the chain so far to the object.为了跟踪整个链,您将到目前为止的链传递给 object。

Something like:就像是:

class AccessTracker:
    def __init__(self, path=()):
        self._path = path

    def __getattr__(self, name):
        print('Accessed %s in %s' % (name, self._path))
        return AccessTracker(self._path + (name,))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM