Python中的空类对象 [英] Empty class object in Python
问题描述
我正在教授有关面向对象程序设计的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"
有趣!
我想知道是否有一种方法可以为此类实例动态定义函数?像这样:
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!'
这在我的Python解释器中不起作用,但是还有另一种方法吗?
This doesn't work in my Python interpreter, but is there another way of doing it?
推荐答案
一个类或多或少是对象的属性dict
的精美包装.当实例化一个类时,您可以为其分配属性,这些属性将存储在foo.__dict__
中.同样,您可以在foo.__dict__
中查找您已经编写的所有属性.
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 in foo.__dict__
; likewise, you can look in foo.__dict__
for any attributes you have already written.
这意味着您可以执行一些巧妙的动态操作,例如:
This means you can do some neat dynamic things like:
class Employee: pass
def foo(self): pass
Employee.foo = foo
,以及分配给特定实例. (添加了self
参数)
as well as assigning to a particular instance. ( added self
parameter)
这篇关于Python中的空类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!