Python 中的空类对象
我正在教授面向对象编程的 Python 课程,当我温习如何解释类时,我看到了一个空的类定义:
class Employee:
pass
然后该示例继续为该类的对象定义名称和其他属性:
john = Employee()
john.full_name = "john doe"
有趣的!
我想知道是否有一种方法可以为这样的类的实例动态定义函数?类似于:
john.greet() = print 'Hello, World!'
这在我的Python解释器中不起作用,但是还有其他方法吗?
I'm teaching a Python class on object-oriented programming and as I'm brushing up on how to explain classes, I saw an empty class definition:
class Employee:
pass
The example then goes on to define a name and other attributes for an object of this class:
john = Employee()
john.full_name = "john doe"
Interesting!
I'm wondering if there's a way to dynamically define a function for an instance of a class like this? something like:
john.greet() = print 'Hello, World!'
This doesn't work in my Python interpreter, but is there another way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
类或多或少是对象属性的
dict
的精美包装。当您实例化一个类时,您可以为其分配属性,这些属性将存储在 foo.__dict__ 中;同样,您可以在 foo.__dict__ 中查找您已经编写的任何属性。这意味着您可以执行一些简洁的动态操作,例如:
以及分配给特定实例。 (编辑:添加
self
参数)A class is more or less a fancy wrapper for a
dict
of attributes to objects. When you instantiate a class you can assign to its attributes, and those will be stored infoo.__dict__
; likewise, you can look infoo.__dict__
for any attributes you have already written.This means you can do some neat dynamic things like:
as well as assigning to a particular instance. (EDIT: added
self
parameter)尝试使用 lambda :
您将能够执行以下操作:
编辑:感谢 Thomas K 的注释 - 这适用于
Python 3.2
而不是 Python2,其中print
似乎是statement
。但这适用于lambda
,没有语句(对吗?抱歉,我只知道python3.2
(:)Try with
lambda
:The you'll be able to do:
EDIT: Thanks Thomas K for the note - this works on
Python 3.2
and not for Python2, whereprint
appeared to bestatement
. But this will work forlambda
s, without statements (right? Sorry, I know onlypython3.2
(: )您还可以使用
collection
标准模块中的“命名元组”。命名元组的工作方式与“普通”元组类似,但元素具有名称,并且您可以使用“点语法”访问元素。来自 集合文档:You could also use "named tuples" from the
collection
standard module. Named tuples work like "ordinary" tuples but the elements have names and you can access the elements using the "dot syntax". From the collection docs:您可以使用 AttrDict
从 PyPI 安装 attrdict:
它在其他情况下也很有用 - 例如当您需要对 dict 键进行属性访问时。
You could use AttrDict
Install attrdict from PyPI:
It's useful in other situations too - like when you need attribute access to dict keys.