我在想是否有某种方法可以解包对象属性。通常这样做涉及一系列:
self.x = x
self.y = y
... #etc.
但是应该可以做得更好。
我正在考虑类似的事情:
def __init__(self,x,y,z):
self.(x,y,z) = x,y,z
或者可能:
用 x,y,z 解包(自我)
甚至功能如下:
def __init__(self,x,y,z):
unpack(self,x,y,z)
有任何想法吗?还是有一些更蟒蛇的方式来做到这一点?
我在想是否有某种方法可以解包对象属性。通常这样做涉及一系列:
self.x = x
self.y = y
... #etc.
但是应该可以做得更好。
我正在考虑类似的事情:
def __init__(self,x,y,z):
self.(x,y,z) = x,y,z
或者可能:
用 x,y,z 解包(自我)
甚至功能如下:
def __init__(self,x,y,z):
unpack(self,x,y,z)
有任何想法吗?还是有一些更蟒蛇的方式来做到这一点?
您可能想要使用namedtuple,这正是您想要的:
来自官方 Python 文档的代码示例:
Point = namedtuple('Point', ['x', 'y'], verbose=True)
上面的代码等价于:
class Point(tuple):
'Point(x, y)'
__slots__ = ()
_fields = ('x', 'y')
def __new__(_cls, x, y):
'Create a new instance of Point(x, y)'
return _tuple.__new__(_cls, (x, y))
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Point object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 2:
raise TypeError('Expected 2 arguments, got %d' % len(result))
return result
def __repr__(self):
'Return a nicely formatted representation string'
return 'Point(x=%r, y=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self))
def _replace(_self, **kwds):
'Return a new Point object replacing specified fields with new values'
result = _self._make(map(kwds.pop, ('x', 'y'), _self))
if kwds:
raise ValueError('Got unexpected field names: %r' % kwds.keys())
return result
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
__dict__ = _property(_asdict)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
pass
x = _property(_itemgetter(0), doc='Alias for field number 0')
y = _property(_itemgetter(1), doc='Alias for field number 1')
以下是如何使用它:
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)
值得一提的是,namedtuple它只是一个普通类,您可以创建一个继承自它的类。
我很确定你可以这样做:self.x, self.y, self.z = x, y, z
定义像 unpack(self,x,y,z) 这样的函数可能不是一个好主意,因为该函数不够通用(对象的组合是在运行时定义的)
此处解释了基于属性名称实例化变量的更通用的方法 http://code.activestate.com/recipes/286185-automatically-initializing-instance-variables-from/
class Blahblah:
def __init__(self, *args, **kwargs):
def unpack(vars_name, args, kwargs): #Cant be acceded for some instance in this place
nonlocal self
for i, var in enumerate(vars_name):
exec(f"self.{var}={args[i]}")
for key, value in kwargs.items():
exec(f"self.{key}={value}")
#You must add some validator for de length of args before the next code in this place
vars_for_self = ["a","b","c"]
unpack(vars_for_self, args, kwargs)
del vars_for_self, args, kwargs, unpack #For clean vars in the class instance
#First ways to check de self vars creation
#print(self.__dict__)
#Second way to check
#print(locals()["self"].__dict__)
#Your other methods go here
签到结果
if __name__== "__main__":
#And the last way
c = Blahblah(3,4,5, x=6,y=7,z=0)
#print(c.a)
#print(c.x)
print(c.__dict__)
print(vars(Blahblah.__dict__["__init__"]))