如何在字符串插值中访问实例变量?

时间:2014-03-21 20:03:19

标签: python

我想在实例方法中使用字符串插值:但我不确定如何访问实例变量。

这是基本的类声明,包括构造函数:

class Validation:
    def __init__(self, name, type, count, script):
        self.name = name
        self.type = type
        self.count = count
        self.script = script

这是我们想要访问变量列表的地方。注意“globals()”正确..

    def __repr__(self):
        return "%(self.name)s: %(self.type)s that expects %(self.count)s Rows [%(self.script)s]" %self.__dict__

但这会产生异常

(<type 'exceptions.KeyError'>, KeyError('self.name',), None)

所以问题是:应该用什么代替%self。 dict

2 个答案:

答案 0 :(得分:3)

首先,string interpolation已被string formatting取代,所以让我们更新:

"{self.name}: {self.type} that expects {self.count} Rows [{self.script}]".format(**self.__dict__)

其次,既然你要给它使用dict,那么dict中的键只是变量名,而不是self.varname

"{name}: {type} that expects {count} Rows [{script}]".format(**self.__dict__)

第三,__repr__旨在成为有效的Python代码来重现该对象。也许你打算把它作为__str____repr__应为

"Validation({name},{type},{count},{script})".format(**self.__dict__)
老实说,既然这是不好的做法,那就是:

"Validation({},{},{},{})".format(self.name,self.type,self.count,self.script)

我们试一试:

#DEMO
class Validation(object):
    def __init__(self, name, type_, count, script):
        self.name = name
        self.type = type_
        self.count = count
        self.script = script
    def __repr__(self):
        return "Validation({},{},{},{})".format(self.name,self.type,self.count,self.script)
    def __str__(self):
        return "{}: {} that expects {} Rows [{}]".format(self.name,self.type,self.count,self.script)

>>> v = Validation('MyName','integer',26,lambda x: x)
>>> print(v) # or str(v)
MyName: integer that expects 26 Rows [<function <lambda> at 0x02D75468>]
>>> repr(v)
'Validation(MyName,integer,26,<function <lambda> at 0x02D75468>)'

答案 1 :(得分:1)

您应该省略self.并使用vars()代替__dict__(感谢@roippi):

class Validation:
    def __init__(self, name, type, count, script):
        self.name = name
        self.type = type
        self.count = count
        self.script = script

    def __repr__(self):
        return "%(name)s: %(type)s that expects %(count)s Rows [%(script)s]" % vars(self)


validation = Validation('name', 'type', 'count', 'script')
print validation

打印:

name: type that expects count Rows [script]