[英]Overriding a function in python
I have the following base class (code shortened): 我有以下基类(代码缩短了):
class SignupForm(GroupForm):
username = forms.CharField(
label = _("Username"),
max_length = 30,
widget = forms.TextInput()
)
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
if REQUIRED_EMAIL or EMAIL_VERIFICATION or EMAIL_AUTHENTICATION:
self.fields["email"].label = ugettext("Email")
self.fields["email"].required = True
else:
self.fields["email"].label = ugettext("Email (optional)")
self.fields["email"].required = False
def after_signup(self, user, **kwargs):
"""
An extension point for subclasses.
"""
pass
What I wanna do is override the after_signup()
function and the username
field like so: 我想做的是重写after_signup()
函数和username
after_signup()
段,如下所示:
class CompanySignupForm(SignupForm):
#TODO: override fields for company signup form
username = forms.CharField(
label = _("Username TEST"),
max_length = 30,
widget = forms.TextInput()
)
def after_signup(self, user, **kwargs):
"""
An extension point for subclasses.
"""
print str('after_signup is has been overwritten')
My Problem: Only the username field shows the desired behavior. 我的问题:只有用户名字段显示所需的行为。 The after_signup()
function get never called. after_signup()
函数永远不会被调用。 Instead the after_signup()
function of the base class SignupForm
gets called. 而是调用基类SignupForm
的after_signup()
函数。 What am I doning wrong? 我在做什么错?
EDIT: 编辑:
the imports:
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _, ugettext
instantiating CompanySignupForm: 实例化CompanySignupForm:
url(r"^signup/$", CompanySignupForm.as_view(), name="acct_signup")
after_signup() is beeing called from a function in the base class: 从基类中的函数调用after_signup():
def save(self, request=None):
# more code here
# ...
self.after_signup(new_user)
Use isinstance()
to check an instance's type and .__class__
to make sure you are instantiating CompanySignupForm
. 使用isinstance()
检查实例的类型,并使用.__class__
来确保实例化CompanySignupForm
。
Also you might want to create an __init__
method on the CompanySignupForm
to ensure it's not just instantiating the super class. 另外,您可能想在CompanySignupForm
上创建__init__
方法,以确保它不只是实例化超类。
Note: Reading your edit more closely your not calling after_signup directly the base class function save is right? 注意:更仔细地阅读您的编辑您不直接调用after_signup基类函数保存对吗? This will then call it's local method after_signup if it exists. 然后,如果存在,它将调用它的本地方法after_signup。 I'd take that function out of the base class and force it to call the inherited functions 我将从基类中删除该函数,并强制它调用继承的函数
To check the version run: 要检查版本,请运行:
signup = CompanySignupForm.as_view()
print signup.__class__
url(r"^signup/$", signup, name="acct_signup")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.