向python对象添加新成员变量? [英] Adding new member variables to python objects?

查看:116
本文介绍了向python对象添加新成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读 Magnus Lie Hetland 的从新手到专业人士的 Python 入门",今天让我印象深刻的是对象创建新成员变量的能力,即使这些成员变量从对象是创建"的.下面是一个例子:

I have started reading the "Beginning python from novice to professional" by Magnus Lie Hetland, and what struck me today is an ability of an objects to create new member variables, even though those member variables were not present in the class from which the object was "created". Here is an example:

class Test:
    pass

b = Test()

b.variable1 = 12
b.variable2 = "Jim"

print b.variable1
print b.variable2

直到现在,我认为对象只能更改父类中存在的成员值,而不能凭空创建新的?顺便说一句,我之前没有编程或 Python 方面的知识.

Until now I though that objects could only change the member values present in parent class, but not create new ones out of thin air? Btw I had no prior knowledge of programming or python.

推荐答案

Python 文档.根据它,此符号用于将几个命名项绑定在一起.这正是 Python 允许你做的.

A similar example is given in the Python Docs. According to it, this notation is used for binding together a couple of named items. This is just what Python allows you to do.

这篇关于向python对象添加新成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆