目标是创建一个行为类似于数据库结果集的模拟类。

例如,如果数据库查询使用 dict 表达式返回, {'ab':100, 'cd':200}, ,那么我想看看:

>>> dummy.ab
100

起初我想也许我可以这样做:

ks = ['ab', 'cd']
vs = [12, 34]
class C(dict):
    def __init__(self, ks, vs):
        for i, k in enumerate(ks):
            self[k] = vs[i]
            setattr(self, k, property(lambda x: vs[i], self.fn_readyonly))

    def fn_readonly(self, v)
        raise "It is ready only"

if __name__ == "__main__":
    c = C(ks, vs)
    print c.ab

c.ab 相反,返回一个属性对象。

更换 setattrk = property(lambda x: vs[i]) 根本没有用。

那么在运行时创建实例属性的正确方法是什么?

附:我知道有一个替代方案 怎么样 __getattribute__ 使用的方法?

有帮助吗?

解决方案

我想我应该扩大这个答案,现在我懂事了,知道是怎么回事。迟到总比不到好。

可以的属性动态地添加到一个类。但是,这是美中不足的是:你必须将它添加到的

>>> class Foo(object):
...     pass
... 
>>> foo = Foo()
>>> foo.a = 3
>>> Foo.b = property(lambda self: self.a + 1)
>>> foo.b
4

一个property实际上是一个简单的实现的事情称为描述符。它是一个对象,它提供自定义处理一个给定属性,在给定的类。有点像一个方式对因子巨大if树出__getattribute__的。

当我在上面的例子中要求foo.b,Python看到,关于类中定义的b实现描述符协议哪位只是意味着它是与__get____set__,或__delete__方法的对象。该描述称处理该属性的责任,所以Python会自动调用Foo.b.__get__(foo, Foo),并且返回值被传递回你的属性值。在property的情况下,每一种方法只是调用fgetfset,或者你传递给fdel构造property

描述符是真的暴露其整个OO实现的管道的Python的方式。事实上,还有另一种类型的描述符的甚至比property更常见。

>>> class Foo(object):
...     def bar(self):
...         pass
... 
>>> Foo().bar
<bound method Foo.bar of <__main__.Foo object at 0x7f2a439d5dd0>>
>>> Foo().bar.__get__
<method-wrapper '__get__' of instancemethod object at 0x7f2a43a8a5a0>

在简陋的方法仅仅是另一种描述符。它的调用实例作为第一个参数__get__固定物;实际上,它这样做:

def __get__(self, instance, owner):
    return functools.partial(self.function, instance)

不管怎样,我怀疑这就是为什么描述符只在类的工作:他们的东西形式化是摆在首位的权力等级。他们甚至例外:可以很明显的分配描述符一类,和类本身type的实例!事实上,试图读取Foo.b仍称property.__get__;它只是为成语时作为类属性访问的描述符返回自己。

我觉得这很酷,几乎所有的Python的面向对象的系统可以在Python中表示。 :)

哦,我写了一个罗嗦博客文章描述符的一段时间回来,如果你有兴趣。

其他提示

  

的目标是创建一个模拟类行为类似于分贝结果集。

所以,你要的是一本字典,你能拼出一个[ 'B']作为A·B?

这很简单:

class atdict(dict):
    __getattr__= dict.__getitem__
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

您不需要使用属性为。只是覆盖__setattr__使他们只读。

class C(object):
    def __init__(self, keys, values):
        for (key, value) in zip(keys, values):
            self.__dict__[key] = value

    def __setattr__(self, name, value):
        raise Exception("It is read only!")

多田。

>>> c = C('abc', [1,2,3])
>>> c.a
1
>>> c.b
2
>>> c.c
3
>>> c.d
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'd'
>>> c.d = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __setattr__
Exception: It is read only!
>>> c.a = 'blah'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __setattr__
Exception: It is read only!

如何动态向Python类添加属性?

假设您有一个想要添加属性的对象。通常,当我需要开始管理对具有下游用途的代码中的属性的访问时,我希望使用属性,以便我可以维护一致的 API。现在,我通常会将它们添加到定义对象的源代码中,但假设您没有该访问权限,或者您需要以编程方式真正动态地选择函数。

创建一个类

使用基于的示例 的文档 property, ,让我们创建一个具有“隐藏”属性的对象类并创建它的实例:

class C(object):
    '''basic class'''
    _x = None

o = C()

在 Python 中,我们期望有一种明显的做事方式。但是,在这种情况下,我将展示两种方法:带装饰器符号和不带装饰器符号。首先,没有装饰器符号。这对于获取器、设置器或删除器的动态分配可能更有用。

动态(又名猴子补丁)

让我们为我们的班级创建一些:

def getx(self):
    return self._x

def setx(self, value):
    self._x = value

def delx(self):
    del self._x

现在我们将这些分配给属性。请注意,我们可以在这里以编程方式选择我们的函数,回答动态问题:

C.x = property(getx, setx, delx, "I'm the 'x' property.")

及用法:

>>> o.x = 'foo'
>>> o.x
'foo'
>>> del o.x
>>> print(o.x)
None
>>> help(C.x)
Help on property:

    I'm the 'x' property.

装饰器

我们可以像上面使用装饰器符号一样做同样的事情,但在这种情况下,我们 必须 将所有方法命名为相同的名称(我建议将其与属性保持相同),因此编程分配并不像使用上述方法那么简单:

@property
def x(self):
    '''I'm the 'x' property.'''
    return self._x

@x.setter
def x(self, value):
    self._x = value

@x.deleter
def x(self):
    del self._x

并将属性对象及其预配置的设置器和删除器分配给该类:

C.x = x

及用法:

>>> help(C.x)
Help on property:

    I'm the 'x' property.

>>> o.x
>>> o.x = 'foo'
>>> o.x
'foo'
>>> del o.x
>>> print(o.x)
None

我问了一个与之相似的问题在这个堆栈溢出后以创建类工厂这创造简单类型。结果是这个答案这有类工厂的工作版本。 下面是答案的一个片段:

def Struct(*args, **kwargs):
    def init(self, *iargs, **ikwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)
        for i in range(len(iargs)):
            setattr(self, args[i], iargs[i])
        for k,v in ikwargs.items():
            setattr(self, k, v)

    name = kwargs.pop("name", "MyStruct")
    kwargs.update(dict((k, None) for k in args))
    return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()})

>>> Person = Struct('fname', 'age')
>>> person1 = Person('Kevin', 25)
>>> person2 = Person(age=42, fname='Terry')
>>> person1.age += 10
>>> person2.age -= 10
>>> person1.fname, person1.age, person2.fname, person2.age
('Kevin', 35, 'Terry', 32)
>>>

您可以使用这一些变化,以创建默认值,这是你的目标(也有在这个问题与这涉及一个答案)。

您不能在运行时一个新的property()添加到一个实例,因为属性数据描述符。相反,你必须动态以上的实例处理数据描述符创建新的类,或过载__getattribute__

不知道如果我完全理解这个问题,但你可以在运行时使用内置类的__dict__修改实例属性:

class C(object):
    def __init__(self, ks, vs):
        self.__dict__ = dict(zip(ks, vs))


if __name__ == "__main__":
    ks = ['ab', 'cd']
    vs = [12, 34]
    c = C(ks, vs)
    print(c.ab) # 12

对于那些来自搜索引擎的,这里有两件事情我一直在寻找谈论的动态的属性时为:

class Foo:
    def __init__(self):
        # we can dynamically have access to the properties dict using __dict__
        self.__dict__['foo'] = 'bar'

assert Foo().foo == 'bar'


# or we can use __getattr__ and __setattr__ to execute code on set/get
class Bar:
    def __init__(self):
        self._data = {}
    def __getattr__(self, key):
        return self._data[key]
    def __setattr__(self, key, value):
        self._data[key] = value

bar = Bar()
bar.foo = 'bar'
assert bar.foo == 'bar'

如果你想要把动态创建的性能__dict__好。 __getattr__好需要的值时,仅做一些事情,比如查询数据库。的设置/获取组合是良好的简化访问存储在类(如在上面的例子)数据。

如果你只想要一个动态属性,看看在财产( )内置函数。

要实现的最佳方式是通过定义__slots__。这样,你的情况下,不能有新的属性。

ks = ['ab', 'cd']
vs = [12, 34]

class C(dict):
    __slots__ = []
    def __init__(self, ks, vs): self.update(zip(ks, vs))
    def __getattr__(self, key): return self[key]

if __name__ == "__main__":
    c = C(ks, vs)
    print c.ab

,打印12

    c.ab = 33

这给出了:AttributeError: 'C' object has no attribute 'ab'

又一个示例如何实现期望的效果

class Foo(object):

    _bar = None

    @property
    def bar(self):
        return self._bar

    @bar.setter
    def bar(self, value):
        self._bar = value

    def __init__(self, dyn_property_name):
        setattr(Foo, dyn_property_name, Foo.bar)

所以,现在我们可以做的东西,如:

>>> foo = Foo('baz')
>>> foo.baz = 5
>>> foo.bar
5
>>> foo.baz
5

可以使用下面的代码来更新类属性使用字典对象:

class ExampleClass():
    def __init__(self, argv):
        for key, val in argv.items():
            self.__dict__[key] = val

if __name__ == '__main__':
    argv = {'intro': 'Hello World!'}
    instance = ExampleClass(argv)
    print instance.intro

这似乎工作(见下文):

class data(dict,object):
    def __init__(self,*args,**argd):
        dict.__init__(self,*args,**argd)
        self.__dict__.update(self)
    def __setattr__(self,name,value):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be set"%(name,self.__class__.__name__)
    def __delattr__(self,name):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be deleted"%(name,self.__class__.__name__)

如果您需要更复杂的行为,随意修改你的答案。

修改

下面将可能更内存效率为大数据集:

class data(dict,object):
    def __init__(self,*args,**argd):
        dict.__init__(self,*args,**argd)
    def __getattr__(self,name):
        return self[name]
    def __setattr__(self,name,value):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be set"%(name,self.__class__.__name__)
    def __delattr__(self,name):
        raise AttributeError,"Attribute '%s' of '%s' object cannot be deleted"%(name,self.__class__.__name__)

要回答你的问题的主旨,你想有一个只读从字典作为一个不变的数据源属性:

  

的目标是创建一个模拟类行为类似于分贝结果集。

     

因此,例如,如果一个数据库查询返回,使用一个字典表达,   {'ab':100, 'cd':200},那么我会看到

>>> dummy.ab
100

我将演示如何使用namedtuplecollections模块来完成眼前这个:

import collections

data = {'ab':100, 'cd':200}

def maketuple(d):
    '''given a dict, return a namedtuple'''
    Tup = collections.namedtuple('TupName', d.keys()) # iterkeys in Python2
    return Tup(**d)

dummy = maketuple(data)
dummy.ab

返回100

class atdict(dict):
  def __init__(self, value, **kwargs):
    super().__init__(**kwargs)
    self.__dict = value

  def __getattr__(self, name):
    for key in self.__dict:
      if type(self.__dict[key]) is list:
        for idx, item in enumerate(self.__dict[key]):
          if type(item) is dict:
            self.__dict[key][idx] = atdict(item)
      if type(self.__dict[key]) is dict:
        self.__dict[key] = atdict(self.__dict[key])
    return self.__dict[name]



d1 = atdict({'a' : {'b': [{'c': 1}, 2]}})

print(d1.a.b[0].c)

和输出是:

>> 1

kjfletch

扩展的想法
# This is my humble contribution, extending the idea to serialize
# data from and to tuples, comparison operations and allowing functions
# as default values.

def Struct(*args, **kwargs):
    FUNCTIONS = (types.BuiltinFunctionType, types.BuiltinMethodType, \
                 types.FunctionType, types.MethodType)
    def init(self, *iargs, **ikwargs):
        """Asume that unamed args are placed in the same order than
        astuple() yields (currently alphabetic order)
        """
        kw = list(self.__slots__)

        # set the unnamed args
        for i in range(len(iargs)):
            k = kw.pop(0)
            setattr(self, k, iargs[i])

        # set the named args
        for k, v in ikwargs.items():
            setattr(self, k, v)
            kw.remove(k)

        # set default values
        for k in kw:
            v = kwargs[k]
            if isinstance(v, FUNCTIONS):
                v = v()
            setattr(self, k, v)

    def astuple(self):
        return tuple([getattr(self, k) for k in self.__slots__])

    def __str__(self):
        data = ['{}={}'.format(k, getattr(self, k)) for k in self.__slots__]
        return '<{}: {}>'.format(self.__class__.__name__, ', '.join(data))

    def __repr__(self):
        return str(self)

    def __eq__(self, other):
        return self.astuple() == other.astuple()

    name = kwargs.pop("__name__", "MyStruct")
    slots = list(args)
    slots.extend(kwargs.keys())
    # set non-specific default values to None
    kwargs.update(dict((k, None) for k in args))

    return type(name, (object,), {
        '__init__': init,
        '__slots__': tuple(slots),
        'astuple': astuple,
        '__str__': __str__,
        '__repr__': __repr__,
        '__eq__': __eq__,
    })


Event = Struct('user', 'cmd', \
               'arg1', 'arg2',  \
               date=time.time, \
               __name__='Event')

aa = Event('pepe', 77)
print(aa)
raw = aa.astuple()

bb = Event(*raw)
print(bb)

if aa == bb:
    print('Are equals')

cc = Event(cmd='foo')
print(cc)

输出:

<Event: user=pepe, cmd=77, arg1=None, arg2=None, date=1550051398.3651814>
<Event: user=pepe, cmd=77, arg1=None, arg2=None, date=1550051398.3651814>
Are equals
<Event: user=None, cmd=foo, arg1=None, arg2=None, date=1550051403.7938335>

虽然很多答案给出,我无法找到一个我很高兴。我想通了,我自己的解决方案,这使得property工作的动态情况。源到回答原来的问题:

#!/usr/local/bin/python3

INITS = { 'ab': 100, 'cd': 200 }

class DP(dict):
  def __init__(self):
    super().__init__()
    for k,v in INITS.items():
        self[k] = v 

def _dict_set(dp, key, value):
  dp[key] = value

for item in INITS.keys():
  setattr(
    DP,
    item,
    lambda key: property(
      lambda self: self[key], lambda self, value: _dict_set(self, key, value)
    )(item)
  )

a = DP()
print(a)  # {'ab': 100, 'cd': 200}
a.ab = 'ab100'
a.cd = False
print(a.ab, a.cd) # ab100 False

东西对我的作品是这样的:

class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, x):
        self._x = x

    def d(self):
        del self._x

    def s2(self,x):
        self._x=x+x

    x=property(g,s,d)


c = C()
c.x="a"
print(c.x)

C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x)

输出

a
aa

这是比OP想有点不同,但我叮叮当当我的大脑,直到我得到了一个工作的解决方案,所以我把这里的下一个家伙/加仑

我需要一种方法来指定动态setter和getter。

class X:
    def __init__(self, a=0, b=0, c=0):
        self.a = a
        self.b = b
        self.c = c

    @classmethod
    def _make_properties(cls, field_name, inc):
        _inc = inc

        def _get_properties(self):
            if not hasattr(self, '_%s_inc' % field_name):
                setattr(self, '_%s_inc' % field_name, _inc)
                inc = _inc
            else:
                inc = getattr(self, '_%s_inc' % field_name)

            return getattr(self, field_name) + inc

        def _set_properties(self, value):
            setattr(self, '_%s_inc' % field_name, value)

        return property(_get_properties, _set_properties)

我知道我的领域提前所以我要去创建我的属性。注意:你不能做到这一点每个实例,这些属性将存在于类!

for inc, field in enumerate(['a', 'b', 'c']):
    setattr(X, '%s_summed' % field, X._make_properties(field, inc))

现在让我们来测试这一切..

x = X()
assert x.a == 0
assert x.b == 0
assert x.c == 0

assert x.a_summed == 0  # enumerate() set inc to 0 + 0 = 0
assert x.b_summed == 1  # enumerate() set inc to 1 + 0 = 1
assert x.c_summed == 2  # enumerate() set inc to 2 + 0 = 2

# we set the variables to something
x.a = 1
x.b = 2
x.c = 3

assert x.a_summed == 1  # enumerate() set inc to 0 + 1 = 1
assert x.b_summed == 3  # enumerate() set inc to 1 + 2 = 3
assert x.c_summed == 5  # enumerate() set inc to 2 + 3 = 5

# we're changing the inc now
x.a_summed = 1 
x.b_summed = 3 
x.c_summed = 5

assert x.a_summed == 2  # we set inc to 1 + the property was 1 = 2
assert x.b_summed == 5  # we set inc to 3 + the property was 2 = 5
assert x.c_summed == 8  # we set inc to 5 + the property was 3 = 8

是否混乱?是的,对不起,我不能拿出任何有意义的现实世界的例子。此外,这是不适合宛然的光。

只有这样,才能动态附加属性是创建一个新的类及其实例与您的新属性。

class Holder: p = property(lambda x: vs[i], self.fn_readonly)
setattr(self, k, Holder().p)

最近我遇到了类似的问题,我想出了利用__getattr____setattr__的,我希望它处理的,其他的一切被传递到原件,性能的解决方案。

class C(object):
    def __init__(self, properties):
        self.existing = "Still Here"
        self.properties = properties

    def __getattr__(self, name):
        if "properties" in self.__dict__ and name in self.properties:
            return self.properties[name] # Or call a function, etc
        return self.__dict__[name]

    def __setattr__(self, name, value):
        if "properties" in self.__dict__ and name in self.properties:
            self.properties[name] = value
        else:
            self.__dict__[name] = value

if __name__ == "__main__":
    my_properties = {'a':1, 'b':2, 'c':3}
    c = C(my_properties)
    assert c.a == 1
    assert c.existing == "Still Here"
    c.b = 10
    assert c.properties['b'] == 10

许多提供的答案需要每个属性如此多的行,即 / 和 / 或 - 我认为这是一个丑陋或乏味的实现,因为多个属性需要重复性等。我更喜欢不断地简化/简化它们,直到它们无法再简化或者直到这样做没有多大作用为止。

简而言之:在已完成的作品中,如果我重复 2 行代码,我通常会将其转换为单行辅助函数,依此类推......我将数学或奇数参数(例如(start_x,start_y,end_x,end_y)简化为(x,y,w,h),即x,y,x + w,y + h(有时需要min / max或如果w / h)是负数并且实现不喜欢它,我将从 x / y 和 abs w / h 中减去。ETC..)。

覆盖内部 getter / setter 是一种不错的方法,但问题是您需要为每个类执行此操作,或者将该类作为该基类的父级...这对我不起作用,因为我更愿意自由选择子节点/父节点进行继承、子节点等。

我创建了一个解决方案,可以在不使用 Dict 数据类型来提供数据的情况下回答问题,因为我发现输入数据非常繁琐,等等......

我的解决方案要求您在类上方添加 2 行,为要添加属性的类创建基类,然后每行 1 行,您可以选择添加回调来控制数据,在数据更改时通知您,限制可以根据值和/或数据类型设置的数据等等。

您还可以选择使用 _object.x、_object.x = value、_object.GetX( )、_object.SetX( value ),它们的处理方式相同。

此外,这些值是分配给类实例的唯一非静态数据,但实际属性分配给类意味着您不想重复的事情,不需要重复...您可以指定一个默认值,这样 getter 就不需要每次都需要它,尽管有一个选项可以覆盖默认的默认值,并且还有另一个选项,因此 getter 通过覆盖默认返回值来返回原始存储值(注意:此方法意味着仅在分配值时才分配原始值,否则为 None - 当值重置时,则分配 None 等。)

还有许多辅助函数 - 添加的第一个属性向类添加了 2 个左右的辅助函数以引用实例值...它们是 ResetAccessors( _key, ..) varargs 重复(所有都可以使用第一个命名的 args 重复)和 SetAccessors( _key, _value ) ,可以选择将更多内容添加到主类中以提高效率 - 计划的内容是:一种将访问器分组在一起的方法,因此,如果您每次都倾向于一次重置几个访问器,则可以将它们分配到一个组并重置该组,而不是每次都重复指定的键等等。

实例/原始存储值存储在 班级。, , 班上。引用保存属性的静态变量/值/函数的访问器类。_班级。是属性本身,在设置/获取等期间通过实例类访问时调用。

Accessor _class.__ 指向类,但因为它是内部的,所以需要在类中分配,这就是为什么我选择使用 __Name = AccessorFunc( ...)来分配它,每个属性一行,有许多可选参数可供使用(使用键控可变参数,因为它们更容易、更有效地识别和维护)...

正如前面提到的,我还创建了很多函数,其中一些使用 访问器函数信息,因此不需要调用它(因为目前有点不方便 - 现在您需要使用 _class..FunctionName( _class_instance, args ) - 我通过添加运行这个位马拉松的函数,或者通过将访问器添加到对象并使用 self (命名为 this )来使用堆栈/跟踪来获取实例引用来获取值指出它们用于实例并保留对 self、AccessorFunc 类引用以及函数定义中的其他信息的访问)。

虽然还没有完全完成,但它是一个绝佳的立足点。笔记:如果不使用 __Name = AccessorFunc( ...)来创建属性,即使我在 init 函数中定义了 __ 键,您也无法访问它。如果你这样做了,那就没有问题了。

还:请注意,名称和密钥不同......名称是“正式的”,用于创建函数名称,密钥用于数据存储和访问。即 _class.x,其中小写 x 是关键,名称将是大写 X,以便 GetX( ) 是函数而不是看起来有点奇怪的 Getx( )。这允许 self.x 工作并且看起来合适,而且还允许 GetX( ) 并且看起来合适。

我有一个示例类,其键/名称相同,但显示不同。创建了很多辅助函数来输出数据(注意:并非所有这些都已完成),因此您可以看到发生了什么。

当前使用 key 的函数列表:x,姓名:X 输出为:

这绝不是一个全面的列表 - 在发布时还有一些尚未列入其中......

_instance.SetAccessors( _key, _value [ , _key, _value ] .. )                   Instance Class Helper Function: Allows assigning many keys / values on a single line - useful for initial setup, or to minimize lines.    In short: Calls this.Set<Name>( _value ) for each _key / _value pairing.
_instance.ResetAccessors( _key [ , _key ] .. )                                 Instance Class Helper Function: Allows resetting many key stored values to None on a single line.                                           In short: Calls this.Reset<Name>() for each name provided.


Note: Functions below may list self.Get / Set / Name( _args ) - self is meant as the class instance reference in the cases below - coded as this in AccessorFuncBase Class.

this.GetX( _default_override = None, _ignore_defaults = False )                 GET:            Returns    IF ISSET: STORED_VALUE .. IF IGNORE_DEFAULTS: None  .. IF PROVIDED: DEFAULT_OVERRIDE ELSE: DEFAULT_VALUE       100
this.GetXRaw( )                                                                 RAW:            Returns    STORED_VALUE                                                                                                     100
this.IsXSet( )                                                                  ISSET:          Returns    ( STORED_VALUE != None )                                                                                         True

this.GetXToString( )                                                            GETSTR:         Returns    str( GET )                                                                                                       100
this.GetXLen( _default_override = None, _ignore_defaults = False )              LEN:            Returns    len( GET )                                                                                                       3
this.GetXLenToString( _default_override = None, _ignore_defaults = False )      LENSTR:         Returns    str( len( GET ) )                                                                                                3
this.GetXDefaultValue( )                                                        DEFAULT:        Returns    DEFAULT_VALUE                                                                                                    1111

this.GetXAccessor( )                                                            ACCESSOR:       Returns    ACCESSOR_REF ( self.__<key> )                                                                                    [ AccessorFuncBase ] Key: x : Class ID: 2231452344344 : self ID: 2231448283848        Default: 1111       Allowed Types: {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"}     Allowed Values: None
this.GetXAllowedTypes( )                                                        ALLOWED_TYPES:  Returns    Allowed Data-Types                                                                                               {"<class 'int'>": "<class 'type'>", "<class 'float'>": "<class 'type'>"}
this.GetXAllowedValues( )                                                       ALLOWED_VALUES: Returns    Allowed Values                                                                                                   None

this.GetXHelpers( )                                                             HELPERS:        Returns    Helper Functions String List - ie what you're reading now...                                                     THESE ROWS OF TEXT
this.GetXKeyOutput( )                                                           Returns information about this Name / Key                                                                                                   ROWS OF TEXT
this.GetXGetterOutput( )                                                        Returns information about this Name / Key                                                                                                   ROWS OF TEXT

this.SetX( _value )                                                             SET:            STORED_VALUE Setter - ie Redirect to __<Key>.Set                                                                            N / A
this.ResetX( )                                                                  RESET:          Resets STORED_VALUE to None                                                                                                 N / A

this.HasXGetterPrefix( )                                                        Returns Whether or Not this key has a Getter Prefix...                                                                                      True
this.GetXGetterPrefix( )                                                        Returns Getter Prefix...                                                                                                                    Get

this.GetXName( )                                                                Returns Accessor Name - Typically Formal / Title-Case                                                                                       X
this.GetXKey( )                                                                 Returns Accessor Property Key - Typically Lower-Case                                                                                        x
this.GetXAccessorKey( )                                                         Returns Accessor Key - This is to access internal functions, and static data...                                                             __x
this.GetXDataKey( )                                                             Returns Accessor Data-Storage Key - This is the location where the class instance value is stored..                                         _x

输出的一些数据是:

这是使用 Demo 类创建的全新类,除了名称(因此可以输出)之外没有分配任何数据,即 _foo,我使用的变量名...

_foo         --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016

    Key       Getter Value        | Raw Key   Raw / Stored Value       | Get Default Value             Default Value            | Get Allowed Types             Allowed Types                                                              | Get Allowed Values            Allowed Values                                                                                                                                                                                                                   |

    Name:     _foo                | _Name:    _foo                     | __Name.DefaultValue( ):       AccessorFuncDemoClass    | __Name.GetAllowedTypes( )     <class 'str'>                                                              | __Name.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    x:        1111                | _x:       None                     | __x.DefaultValue( ):          1111                     | __x.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __x.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    y:        2222                | _y:       None                     | __y.DefaultValue( ):          2222                     | __y.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __y.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    z:        3333                | _z:       None                     | __z.DefaultValue( ):          3333                     | __z.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __z.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Blah:     <class 'int'>       | _Blah:    None                     | __Blah.DefaultValue( ):       <class 'int'>            | __Blah.GetAllowedTypes( )     <class 'str'>                                                              | __Blah.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Width:    1                   | _Width:   None                     | __Width.DefaultValue( ):      1                        | __Width.GetAllowedTypes( )    (<class 'int'>, <class 'bool'>)                                            | __Width.GetAllowedValues( )   Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Height:   0                   | _Height:  None                     | __Height.DefaultValue( ):     0                        | __Height.GetAllowedTypes( )   <class 'int'>                                                              | __Height.GetAllowedValues( )  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |
    Depth:    2                   | _Depth:   None                     | __Depth.DefaultValue( ):      2                        | __Depth.GetAllowedTypes( )    Saved Value Restricted to Authorized Values ONLY                           | __Depth.GetAllowedValues( )   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |


this.IsNameSet( ):    True      this.GetName( ):     _foo                     this.GetNameRaw( ):    _foo                     this.GetNameDefaultValue( ):    AccessorFuncDemoClass    this.GetNameLen( ):    4    this.HasNameGetterPrefix( ):    <class 'str'>                                this.GetNameGetterPrefix( ):    None
this.IsXSet( ):       False     this.GetX( ):        1111                     this.GetXRaw( ):       None                     this.GetXDefaultValue( ):       1111                     this.GetXLen( ):       4    this.HasXGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetXGetterPrefix( ):       None
this.IsYSet( ):       False     this.GetY( ):        2222                     this.GetYRaw( ):       None                     this.GetYDefaultValue( ):       2222                     this.GetYLen( ):       4    this.HasYGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetYGetterPrefix( ):       None
this.IsZSet( ):       False     this.GetZ( ):        3333                     this.GetZRaw( ):       None                     this.GetZDefaultValue( ):       3333                     this.GetZLen( ):       4    this.HasZGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetZGetterPrefix( ):       None
this.IsBlahSet( ):    False     this.GetBlah( ):     <class 'int'>            this.GetBlahRaw( ):    None                     this.GetBlahDefaultValue( ):    <class 'int'>            this.GetBlahLen( ):    13   this.HasBlahGetterPrefix( ):    <class 'str'>                                this.GetBlahGetterPrefix( ):    None
this.IsWidthSet( ):   False     this.GetWidth( ):    1                        this.GetWidthRaw( ):   None                     this.GetWidthDefaultValue( ):   1                        this.GetWidthLen( ):   1    this.HasWidthGetterPrefix( ):   (<class 'int'>, <class 'bool'>)              this.GetWidthGetterPrefix( ):   None
this.IsDepthSet( ):   False     this.GetDepth( ):    2                        this.GetDepthRaw( ):   None                     this.GetDepthDefaultValue( ):   2                        this.GetDepthLen( ):   1    this.HasDepthGetterPrefix( ):   None                                         this.GetDepthGetterPrefix( ):   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ):  False     this.GetHeight( ):   0                        this.GetHeightRaw( ):  None                     this.GetHeightDefaultValue( ):  0                        this.GetHeightLen( ):  1    this.HasHeightGetterPrefix( ):  <class 'int'>                                this.GetHeightGetterPrefix( ):  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

这是在按相同顺序为所有 _foo 属性(名称除外)分配以下值之后:'字符串', 1.0, True, 9, 10, False

this.IsNameSet( ):    True      this.GetName( ):     _foo                     this.GetNameRaw( ):    _foo                     this.GetNameDefaultValue( ):    AccessorFuncDemoClass    this.GetNameLen( ):    4    this.HasNameGetterPrefix( ):    <class 'str'>                                this.GetNameGetterPrefix( ):    None
this.IsXSet( ):       True      this.GetX( ):        10                       this.GetXRaw( ):       10                       this.GetXDefaultValue( ):       1111                     this.GetXLen( ):       2    this.HasXGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetXGetterPrefix( ):       None
this.IsYSet( ):       True      this.GetY( ):        10                       this.GetYRaw( ):       10                       this.GetYDefaultValue( ):       2222                     this.GetYLen( ):       2    this.HasYGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetYGetterPrefix( ):       None
this.IsZSet( ):       True      this.GetZ( ):        10                       this.GetZRaw( ):       10                       this.GetZDefaultValue( ):       3333                     this.GetZLen( ):       2    this.HasZGetterPrefix( ):       (<class 'int'>, <class 'float'>)             this.GetZGetterPrefix( ):       None
this.IsBlahSet( ):    True      this.GetBlah( ):     string Blah              this.GetBlahRaw( ):    string Blah              this.GetBlahDefaultValue( ):    <class 'int'>            this.GetBlahLen( ):    11   this.HasBlahGetterPrefix( ):    <class 'str'>                                this.GetBlahGetterPrefix( ):    None
this.IsWidthSet( ):   True      this.GetWidth( ):    False                    this.GetWidthRaw( ):   False                    this.GetWidthDefaultValue( ):   1                        this.GetWidthLen( ):   5    this.HasWidthGetterPrefix( ):   (<class 'int'>, <class 'bool'>)              this.GetWidthGetterPrefix( ):   None
this.IsDepthSet( ):   True      this.GetDepth( ):    9                        this.GetDepthRaw( ):   9                        this.GetDepthDefaultValue( ):   2                        this.GetDepthLen( ):   1    this.HasDepthGetterPrefix( ):   None                                         this.GetDepthGetterPrefix( ):   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
this.IsHeightSet( ):  True      this.GetHeight( ):   9                        this.GetHeightRaw( ):  9                        this.GetHeightDefaultValue( ):  0                        this.GetHeightLen( ):  1    this.HasHeightGetterPrefix( ):  <class 'int'>                                this.GetHeightGetterPrefix( ):  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

_foo         --- MyClass: ---- id( this.__class__ ): 2231452349064 :::: id( this ): 2231448475016

    Key       Getter Value        | Raw Key   Raw / Stored Value       | Get Default Value             Default Value            | Get Allowed Types             Allowed Types                                                              | Get Allowed Values            Allowed Values                                                                                                                                                                                                                   |

    Name:     _foo                | _Name:    _foo                     | __Name.DefaultValue( ):       AccessorFuncDemoClass    | __Name.GetAllowedTypes( )     <class 'str'>                                                              | __Name.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    x:        10                  | _x:       10                       | __x.DefaultValue( ):          1111                     | __x.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __x.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    y:        10                  | _y:       10                       | __y.DefaultValue( ):          2222                     | __y.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __y.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    z:        10                  | _z:       10                       | __z.DefaultValue( ):          3333                     | __z.GetAllowedTypes( )        (<class 'int'>, <class 'float'>)                                           | __z.GetAllowedValues( )       Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Blah:     string Blah         | _Blah:    string Blah              | __Blah.DefaultValue( ):       <class 'int'>            | __Blah.GetAllowedTypes( )     <class 'str'>                                                              | __Blah.GetAllowedValues( )    Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Width:    False               | _Width:   False                    | __Width.DefaultValue( ):      1                        | __Width.GetAllowedTypes( )    (<class 'int'>, <class 'bool'>)                                            | __Width.GetAllowedValues( )   Saved Value Restrictions Levied by Data-Type                                                                                                                                                                                     |
    Height:   9                   | _Height:  9                        | __Height.DefaultValue( ):     0                        | __Height.GetAllowedTypes( )   <class 'int'>                                                              | __Height.GetAllowedValues( )  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |
    Depth:    9                   | _Depth:   9                        | __Depth.DefaultValue( ):      2                        | __Depth.GetAllowedTypes( )    Saved Value Restricted to Authorized Values ONLY                           | __Depth.GetAllowedValues( )   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)                                                                                                                                                                                                   |

请注意,由于数据类型或值限制,某些数据未分配 - 这是设计使然。setter 禁止分配不良数据类型或值,甚至禁止分配为默认值(除非您覆盖默认值保护行为)

代码尚未发布在这里,因为在示例和解释之后我没有空间......也因为它会改变。

请注意:在发布本文时,文件很混乱 - 这将会改变。但是,如果您在 Sublime Text 中运行它并编译它,或者从 Python 运行它,它将编译并吐出大量信息 - AccessorDB 部分尚未完成(这将用于更新 Print Getters 和 GetKeyOutput 帮助程序)函数以及被更改为实例函数,可能放入单个函数并重命名 - 寻找它..)

下一个:运行它并不需要一切 - 底部的许多注释内容是用于调试的更多信息 - 当您下载它时它可能不存在。如果是,您应该能够取消注释并重新编译以获得更多信息。

我正在寻找需要 MyClassBase 的解决方法:通过,MyClass(MyClassBase):...- 如果您知道解决方案 - 发布它。

类中唯一需要的是 __ 行 - 斯特 用于调试 在里面 - 它们可以从演示类中删除,但您需要注释掉或删除下面的一些行(_foo / 2 / 3)。

顶部的 String、Dict 和 Util 类是我的 Python 库的一部分 - 它们并不完整。我从图书馆复制了一些我需要的东西,并创建了一些新的。完整的代码将链接到完整的库,并将包含它以及提供更新的调用和删除代码(实际上,剩下的唯一代码将是演示类和打印语句 - AccessorFunc 系统将移至库中)。 ..

部分文件:

##
## MyClass Test AccessorFunc Implementation for Dynamic 1-line Parameters
##
class AccessorFuncDemoClassBase( ):
    pass
class AccessorFuncDemoClass( AccessorFuncDemoClassBase ):
    __Name      = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Name',      default = 'AccessorFuncDemoClass',  allowed_types = ( TYPE_STRING ),                    allowed_values = VALUE_ANY,                 documentation = 'Name Docs',        getter_prefix = 'Get',  key = 'Name',       allow_erroneous_default = False,    options = { } )
    __x         = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'X',         default = 1111,                     allowed_types = ( TYPE_INTEGER, TYPE_FLOAT ),       allowed_values = VALUE_ANY,                 documentation = 'X Docs',           getter_prefix = 'Get',  key = 'x',          allow_erroneous_default = False,    options = { } )
    __Height    = AccessorFuncBase( parent = AccessorFuncDemoClassBase, name = 'Height',    default = 0,                        allowed_types = TYPE_INTEGER,                       allowed_values = VALUE_SINGLE_DIGITS,       documentation = 'Height Docs',      getter_prefix = 'Get',  key = 'Height',     allow_erroneous_default = False,    options = { } )

这种美感使得使用 AccessorFuncs/回调/数据类型/值强制等动态添加属性来创建新类变得异常容易。

目前,链接位于 ( 此链接应反映对文档的更改。): https://www.dropbox.com/s/6gzi44i7dh58v61/dynamic_properties_accessorfuncs_and_more.py?dl=0

还:如果您不使用 Sublime Text,我推荐它而不是 Notepad++、Atom、Visual Code 等,因为正确的线程实现使其使用起来快得多...我还在为它开发一个类似 IDE 的代码映射系统 - 看看: https://bitbucket.org/Acecool/acecoolcodemappingsystem/src/master/ (首先在 Package Manager 中添加 Repo,然后安装插件 - 当版本 1.0.0 准备就绪时,我会将其添加到主插件列表中...)

我希望这个解决方案有帮助...并且一如既往:

仅仅因为它有效,并不意味着它就是正确的 - Josh 'Acecool' Moser

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top