Python 中的空类对象

发布于 2024-11-10 18:43:28 字数 365 浏览 4 评论 0原文

我正在教授面向对象编程的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

握住你手 2024-11-17 18:43:28

类或多或少是对象属性的 dict 的精美包装。当您实例化一个类时,您可以为其分配属性,这些属性将存储在 foo.__dict__ 中;同样,您可以在 foo.__dict__ 中查找您已经编写的任何属性。

这意味着您可以执行一些简洁的动态操作,例如:

class Employee: pass
def foo(self): pass
Employee.foo = foo

以及分配给特定实例。 (编辑:添加 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 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

as well as assigning to a particular instance. (EDIT: added self parameter)

笑忘罢 2024-11-17 18:43:28

尝试使用 lambda :

john.greet = lambda : print( 'hello world!' )

您将能够执行以下操作:

john.greet()

编辑:感谢 Thomas K 的注释 - 这适用于 Python 3.2 而不是 Python2,其中 print 似乎是 statement。但这适用于lambda,没有语句(对吗?抱歉,我只知道python3.2(:)

Try with lambda:

john.greet = lambda : print( 'hello world!' )

The you'll be able to do:

john.greet()

EDIT: Thanks Thomas K for the note - this works on Python 3.2 and not for Python2, where print appeared to be statement. But this will work for lambdas, without statements (right? Sorry, I know only python3.2 (: )

我乃一代侩神 2024-11-17 18:43:28

您还可以使用 collection 标准模块中的“命名元组”。命名元组的工作方式与“普通”元组类似,但元素具有名称,并且您可以使用“点语法”访问元素。来自 集合文档

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)

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:

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
心是晴朗的。 2024-11-17 18:43:28

您可以使用 AttrDict

>>> from attrdict import AttrDict
>>> my_object = AttrDict()
>>> my_object.my_attribute = 'blah'
>>> print my_object.my_attribute
blah
>>> 

从 PyPI 安装 attrdict:

pip install attrdict 

它在其他情况下也很有用 - 例如当您需要对 dict 键进行属性访问时。

You could use AttrDict

>>> from attrdict import AttrDict
>>> my_object = AttrDict()
>>> my_object.my_attribute = 'blah'
>>> print my_object.my_attribute
blah
>>> 

Install attrdict from PyPI:

pip install attrdict 

It's useful in other situations too - like when you need attribute access to dict keys.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文