繁体   English   中英

类python中的字典

[英]A dictionary within a class python

我有一个创建类 (User) 的代码,该类包含两个名为 first_name、last_name 的属性,以及存储在字典 (user_profile) 中的其他几个属性。

现在的问题是,当我从 Class(user) 创建一个实例时,存储在 Dictionary 中的属性没有正确分配到类变量。 代码如下:

class User():
    """ summarize information about a user"""
    def __init__(self, first_name, last_name, **user_profile):
        """initialize the user information like first, last names and others"""

        self.first_name = first_name
        self.last_name = last_name

        # class attributes are stored in a dictionary

        for key, value in user_profile.items():
            self.user_inf = value

# make an instance          
user_prof = User('albert', 'einstein',location = 'princeton', field = 'physics')


print(user_prof.first_name.title() + " " + user_prof.last_name.title() + " " + "used to work in"+ 
   " " + user_prof.user_inf + " " + "at the" + " " + user_prof.user_inf + " " + "department")

结果:

阿尔伯特·爱因斯坦曾在物理系从事物理学工作

预期结果:

阿尔伯特·爱因斯坦曾在普林斯顿物理系工作

如何在实例的正确位置获取字典的值? 有没有办法以正确的顺序索引字典的值?

您的类构造函数中的for循环将user_profile关键参数中的所有值覆盖到self.user_inf ,因此,关键参数user_profile的最后一个值将是self.user_inf的值,要解决此问题,您可以使用:

class User():
    """ summarize information about a user"""
    def __init__(self, first_name, last_name, **user_profile):
        """initialize the user information like first, last names and others"""

        self.first_name = first_name
        self.last_name = last_name

        # class attributes are stored in a dictionary

        self.user_inf = user_profile
user_prof = User('albert', 'einstein',location = 'princeton', field = 'physics')

print(user_prof.first_name.title() + " " + user_prof.last_name.title() + " " + "used to work in"+ 
   " " + user_prof.user_inf['location'] + " " + "at the" + " " + user_prof.user_inf['field'] + " " + "department")

输出:

Albert Einstein used to work in princeton at the physics department

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM