我需要创建一个行为类似于dict
的对象,但是不能使用dict
进行继承。我想将对象传递给以pandas为单位的数组,如果类从set_value
继承而出现尺寸错误,则dict
方法将失败。这意味着我需要我的class
像字典一样工作,但根本不需要继承dict
。大多数示例都展示了如何通过继承`dict来做到这一点。
我不知道该怎么解决的事情:
有没有办法解决这个问题?
###########################################################################
class BaseGeometry(object):
_dict = None
_ao = None
#----------------------------------------------------------------------
def __init__(self, iterable, **kwargs):
if iterable is None:
iterable = {}
for k,v in kwargs.items():
iterable[k] = v
self._dict = iterable
#----------------------------------------------------------------------
def __str__(self):
return str(self._dict)
#----------------------------------------------------------------------
__repr__ = __str__
#----------------------------------------------------------------------
def __getattr__(self, name):
if name == '_dict':
return self._dict
elif name in {'_ao','_type', '_HASARCPY', '_HASSHAPELY',
'_ipython_canary_method_should_not_exist_'}:
return self.__dict__[name]
elif name in self._dict:
return self._dict[name]
else:
raise AttributeError("No such attribute: " + name)
#----------------------------------------------------------------------
def __setattr__(self, name, value):
if name == '_dict':
self.__dict__['_dict'] = value
elif name in {'_ao','_type', '_HASARCPY', '_HASSHAPELY',
'_ipython_canary_method_should_not_exist_'}:
self.__dict__[name] = value
else:
self._dict[name] = value
#----------------------------------------------------------------------
__getitem__ = __getattr__
#----------------------------------------------------------------------
__setitem__ = __setattr__
#----------------------------------------------------------------------
def __delattr__(self, name):
if name in self._dict:
del self._dict[name]
else:
raise AttributeError("No such attribute: " + name)
#----------------------------------------------------------------------
def __iter__(self):
for k,v in self._dict.items():
yield k,v
builtins.ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
这是由于熊猫进行if
检查而引起的。如果它是一个对象,而不是dict
,那么它将起作用。
我也收到此错误:
builtins.ValueError: cannot set using a list-like indexer with a different length than the value