我在 Python 中的超级函数有一些问题。假设我有这两个类:
class A(object):
x=5
def p(self):
print 'A'
def f(self):
self.p()
self.x+=1
class B(A):
def p(self):
print 'B'
def f(self):
super(B, self).f()
self.x*=2
b = B()
b.f()
然后 bx 将等于 12,但该函数将输出“B”,而不是“A”。我需要的是执行 Ap 而不是 Bp,我该如何实现?
谢谢你的时间 :)
编辑:好的,我认为你错过了一些关于我的实际情况的细节,因为我的例子很糟糕。让我们来看看真正的代码。我有这两个类(Django 模型):
class Comment(Insert, models.Model):
content = models.TextField()
sender = models.ForeignKey('logic.User')
sent_on = models.DateTimeField(auto_now_add=True)
def __insert__(self):
self.__notify__()
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
)
def __unicode__(self):
return self.content
class Meta:
abstract = True
class UserComment(Comment):
is_reply = models.BooleanField()
reply_to = models.ForeignKey('self', blank=True,
null=True, related_name='replies')
receiver = models.ForeignKey('User', related_name='comments')
def __insert__(self):
super(UserComment, self).__insert__()
self.__notify__()
def __notification__(self, notification):
if self.is_reply:
return '%s has replied your comment' % self.sender
return super(UserComment, self).__notification__(notification)
def __notify__(self):
# Notification objects "should" be created by Comment's __notify__
Update.objects.create(
object_id=self.id,
target=self.receiver,
type=self.__updatetype__(),
)
@classmethod
@cache(prop_name='_notificationtype')
def __notificationtype__(cls):
return NotificationType.objects.get(name='USER_COMMENT')
@classmethod
@cache(prop_name='_updatetype')
def __updatetype__(cls):
return UpdateType.objects.get(name='USER_COMMENT')
def retrieve_users(self):
return [self.receiver] # retrieve_users MUST return an iterable
问题出在两个模型上的__insert__
和__notify__
方法上。__insert__
是第一次将对象记录到数据库时调用的方法,我主要将其用于通知目的。然后,这就是我想要做的:
- 创建一个 UserComment 对象并保存
- 调用 UserComment 实例的
__insert__
- 调用 Comment's
__insert__
,它应该调用 Comment's__notify__
- 调用 UserComment 实例的
__notify__
from__insert__
这可能以或多或少的简单方式实现,还是我必须重构我的代码?
再次感谢您的所有回答。