當我嘗試從一個帶有元類的類繼承時,我遇到了Python中一些非常奇怪的問題。我有這樣的:帶元類的奇怪繼承
class NotifierMetaclass(type):
def __new__(cls, name, bases, dct):
attrs = ((name, value) for name, value in dct.items()
if not name.startswith('__'))
def wrap_method(meth):
return instance_wrapper()(meth) # instance_wrapper is a decorator of my own
def is_callable(value):
return hasattr(value, '__call__')
decorated_meth = dict(
(name, value) if not is_callable(value)
else (name, wrap_method(value))
for name, value in attrs
)
return super(NotifierMetaclass, cls).__new__(
cls, name, bases, decorated_meth
)
class Notifier(object):
def __init__(self, instance):
self._i = instance
__metaclass__ = NotifierMetaclass
,然後在notifiers.py:
from helpers import Notifier
class CommentNotifier(Notifier):
def __notification__(self, notification):
return '%s has commented on your board' % self.sender
def __notify__(self):
receivers = self.retrieve_users()
notif_type = self.__notificationtype__()
for user in receivers:
Notification.objects.create(
object_id=self.id,
receiver=user,
sender_id=self.sender_id,
type=notif_type
)
然而,當我嘗試導入CommentNotifier返回通知。在外殼:
$ python
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from logic.notifiers import CommentNotifier
>>> CommentNotifier
<class 'helpers.CommentNotifier'>
其實,這是(至少這是我的想法)實際上是相同的問題我一個星期前的一些Django models。起初我認爲它與Django的工作方式有關,但現在我懷疑它更像是一個帶元類和繼承的Python「問題」。
這是一個已知的問題,或者我只是做錯了什麼?希望您能夠幫助我。
編輯:我忘了提及,我將這個「錯誤」歸因於元類,因爲如果我沒有給通告的元類,它按預期工作。
您的示例適用於我。你是不是在「東西」部分忽略了一些重要的東西?請提供一個實際展現你的意思的例子。 – BrenBarn
剛剛編輯了真實案例的代碼 – cronos2
我得到了''(只使用了兩個文件,'helpers.py'和'notifiers.py')和''如果我把它放在一個包裏。儘量減少它,並在各個地方粘貼一些打印語句,以排除您沒有導入您認爲自己的版本的可能性。 –
DSM