多个构造函数在python中,使用继承 [英] Multiple constructors in python, using inheritance
问题描述
我有一个类AbstractDataHandle,他的 init 方法和类Classifier。我想有两个构造函数在Classifier,Java like。一个继承自它的超类,一个全新的。
I have a class AbstractDataHandle, whith his init method, and a class Classifier. I would like to have two constructors in Classifier, Java like. One inherited from it`s superclass, and one brand new.
这将是类似的东西(但我打算保留两个构造函数):
It would be something like (but i intend to "keep" the two constructors):
class AbstractDataHandle():
def __init__(self, elements, attributes, labels):
self._load(elements, attributes, labels)
class Classifier(AbstractDataHandle):
def __init__(self, classifier="LinearSVC", proba=False):
self._fit(classifier, proba)
我可以在一个类中有两个构造函数?
如果是,我可以从一个超类继承一个构造函数,并添加一个新的?
Can i have two constructors in one class? If yes, can i have a constructor inherited from a superclass, and add a new one?
提前感谢。
推荐答案
构造函数必须命名为 __ init __
。并且,与Java不同,Python不允许通过它们的参数类型重载函数或方法。所以,如果你有两个构造函数,它们都将是相同的函数。
Constructors have to be named __init__
. And, unlike Java, Python doesn't allow overloading functions or methods by the type of their arguments. So, if you had two constructors, they would both be the same function.
有几种方法。
使用 @classmethod
作为替代构造函数:
Use @classmethod
s as alternate constructors:
class Breakfast(object):
@classmethod
def from_eggs(cls, eggs):
obj = cls()
obj.spam, obj.eggs = 5, eggs
return obj
@classmethod
def from_spam_and_eggs(cls, spam, eggs):
obj = cls()
obj.spam, obj.eggs = spam, eggs
return obj
从标准库中是 datetime.datetime
,可以用 now
, fromtimestamp
或其他几个替代构造函数,除了默认。
A simple example from the standard library is datetime.datetime
, which can be constructed with now
, fromtimestamp
, or a few other alternate constructors, besides the default.
使用默认值关键字 - 只是,和/或可变参数参数,使单个构造函数可以被称为不同的方式:
Use default-valued, keyword-only, and/or variable-argument parameters to make a single constructor that can be called different ways:
class Breakfast(object):
def __init__(self, eggs=0, spam=5):
self.spam, self.eggs = spam, eggs
int
就是一个例子:你可以从一个字符串和一个基础,或者从一个知道如何将自己转换为整数的参数创建它。
int
is an example of this: You can create it from a string and a base, or from a single argument that knows how to convert itself to an integer.
创建具有不同构造函数的子类:
Create subclasses that each have different constructors:
class Breakfast(object):
pass
class HealthyBreakfast(object):
def __init__(self, spam):
self.spam, self.eggs = spam, 0
class NormalBreakfast(object):
def __init__(self, spam, eggs):
self.spam, self.eggs = spam, eggs
在任何一种情况下,初始化。例如:
In any of these cases, you can factor out commonalities into a single "base" initializer. For example:
class Breakfast(object):
def __init__(self, eggs, spam):
self.spam, self.eggs = spam, eggs
class HealthyBreakfast(object):
def __init__(self, spam):
super(HealthyBreakfast, self).__init__(0, spam)
当然不会是可能有早餐没有垃圾邮件。
Of course in no case is it possible to have breakfast without spam.
这篇关于多个构造函数在python中,使用继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!