Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 访问类';s另一个类中的变量';s def_Python_String_Class_Instance Variables - Fatal编程技术网

Python 访问类';s另一个类中的变量';s def

Python 访问类';s另一个类中的变量';s def,python,string,class,instance-variables,Python,String,Class,Instance Variables,我正在尝试重写Person()类中的str方法: ''类人(对象): 我想找到一种更优雅的方法来返回字符串,如下所示: 鼻子 脖子=某物 … … ... 问题:返回字符串的优雅方式,该字符串看起来像 您可以使用内置的vars函数获取类变量的\uu dict\uu,并使用.format(…和.join(…对其进行格式化 参考: 返回模块、类、实例或任何其他具有\uuuuuuuu dict\uuu属性的对象的\uuuuu dict\uuuuu属性 将值转换为“格式化”表示形式,由大多数

我正在尝试重写Person()类中的str方法:

''类人(对象):

我想找到一种更优雅的方法来返回字符串,如下所示:

鼻子

脖子=某物


...

问题:返回字符串的优雅方式,该字符串看起来像

您可以使用内置的
vars
函数获取类变量的
\uu dict\uu
,并使用
.format(…
.join(…
对其进行格式化


参考

  • 返回模块、类、实例或任何其他具有
    \uuuuuuuu dict\uuu
    属性的对象的
    \uuuuu dict\uuuuu
    属性

  • 将值转换为“格式化”表示形式,由大多数内置类型使用的标准格式化语法控制:

  • 返回一个字符串,该字符串是iterable中字符串的串联


输出

Nose = 1
Neck = 1
RShoulder = None


用Python测试:3.6

当我运行它时,我得到一个错误:AttributeError:'Person'对象没有属性'items'@NickSahno:请参阅上的实时演示。您可能在这部分中有一个打字错误
…vars(self).items()
class Person:
    def __init__(self, **kwargs):
        self.Nose = kwargs.get('Nose', None)
        self.Neck = kwargs.get('Neck', None)
        self.RShoulder = kwargs.get('RShoulder', None)

    def __str__(self):
        return '\n'.join(('{} = {}'
                          .format(k, v) for k, v in vars(self).items()))


p = Person(Nose=1, Neck=1)    
print(p)
Nose = 1
Neck = 1
RShoulder = None