![](/img/trans.png)
[英]Can you set the property of a Python class equal to an empty class object?
[英]Empty class object in Python
我正在教授 Python class 面向對象編程,當我復習如何解釋課程時,我看到了一個空的 class 定義:
class Employee:
pass
然后該示例繼續為此 class 的 object 定義名稱和其他屬性:
john = Employee()
john.full_name = "john doe"
有趣的!
我想知道是否有辦法為這樣的 class 的實例動態定義 function ? 就像是:
john.greet() = print 'Hello, World!'
這在我的 Python 解釋器中不起作用,但是還有其他方法嗎?
class 或多或少是對象屬性dict
的精美包裝器。 當您實例化 class 時,您可以為其分配屬性,這些屬性將存儲在foo.__dict__
; 同樣,您可以在foo.__dict__
中查找您已經編寫的任何屬性。
這意味着您可以執行一些簡潔的動態操作,例如:
class Employee: pass
def foo(self): pass
Employee.foo = foo
以及分配給特定實例。 (編輯:添加self
參數)
嘗試使用lambda
:
john.greet = lambda : print( 'hello world!' )
你將能夠做到:
john.greet()
編輯:感謝Thomas K的注釋 - 這適用於Python 3.2
而不是 Python2,其中print
似乎是statement
。 但這適用於lambda
s,沒有語句(對吧?對不起,我只知道python3.2
(:)
您還可以使用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)
你可以使用 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 鍵進行屬性訪問時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.