我无法找到明确的答案.AFAIK,你不能__init__在Python类中拥有多个函数.那么我该如何解决这个问题呢?
假设我有一个Cheese使用该number_of_holes属性调用的类.我怎样才能有两种创建奶酪对象的方法......
parmesan = Cheese(num_holes = 15)number_of_holes属性:gouda = Cheese()我只想到一种方法来做到这一点,但这似乎有点笨重:
class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
Run Code Online (Sandbox Code Playgroud)
你说什么?还有另外一种方法吗?
假设我有一个类,其成员名为data,这是一个列表.
我希望能够使用例如文件名(包含初始化列表的数据)或实际列表来初始化类.
你这样做的技巧是什么?
你只是看看类型__class__吗?
我可能会缺少一些技巧吗?
我已经习惯了C++,其中按参数类型重载很容易.
是否有可能在Python中重载函数?在C#中,我会做类似的事情
void myfunction (int first, string second)
{
//some code
}
void myfunction (int first, string second , float third)
{
//some different code
}
Run Code Online (Sandbox Code Playgroud)
然后当我调用函数时,它会根据参数的数量区分两者.是否有可能在Python中做类似的事情?
Python 3.4 增加了使用静态方法定义函数重载的功能.这基本上是文档中的示例:
from functools import singledispatch
class TestClass(object):
@singledispatch
def test_method(arg, verbose=False):
if verbose:
print("Let me just say,", end=" ")
print(arg)
@test_method.register(int)
def _(arg):
print("Strength in numbers, eh?", end=" ")
print(arg)
@test_method.register(list)
def _(arg):
print("Enumerate this:")
for i, elem in enumerate(arg):
print(i, elem)
if __name__ == '__main__':
TestClass.test_method(55555)
TestClass.test_method([33, 22, 11])
Run Code Online (Sandbox Code Playgroud)
在其最纯粹的形式中,singledispatch实现依赖于第一个用于标识类型的参数,因此将此功能扩展到实例方法变得棘手.
有没有人有任何关于如何使用(或jerry-rig)此功能以使其与实例方法一起使用的建议?
python single-dispatch instance-method python-3.x python-3.4
我有一个AbstractDataHandle类,它的init方法和类Classifier.我想在Classifier中有两个构造函数,Java就像.一个继承自它的超类,一个全新的.
它会像(但我打算"保留"两个构造函数):
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)
Run Code Online (Sandbox Code Playgroud)
我可以在一个班级中拥有两个构造函数吗?如果是,我可以从超类继承构造函数,并添加一个新的构造函数吗?
先感谢您.
在python中,如果直接将可变类型作为默认参数,则会出现一个众所周知的边缘情况:
def foo(x=[]): return x
y = foo()
y.append(1)
print foo()
Run Code Online (Sandbox Code Playgroud)
通常的解决方法是将参数默认为None然后将其设置在正文中.然而,有3种不同的方法可以做到这一点,其中2种基本相同,但第三种是完全不同的.
def foo(x=None):
if x is None:
x = []
return x
Run Code Online (Sandbox Code Playgroud)
这就是我经常看到的.
def foo(x=None):
x = [] if x is None else x
return x
Run Code Online (Sandbox Code Playgroud)
语义相同.一条线更短,但有些人抱怨python的三元组是不自然的,因为它不是以条件开始并建议避免它.
def foo(x=None):
x = x or []
Run Code Online (Sandbox Code Playgroud)
这是最短的.我今天才了解到这种疯狂.我知道lisp所以这对我来说可能不像一些python程序员那么令人惊讶,但我从没想过这会在python中运行.这种行为是不同的; 如果你传递的东西不是None但是评估为false(比如False),它就不会覆盖默认值.如果默认值不评估false,则无法使用它,因此如果您有非空列表或dict默认值,则无法使用它.但是,根据我的经验,空列表/摘要是99%的感兴趣的案例.
关于哪个是最pythonic的想法?我意识到这里有一个观点要素,但我希望有人可以给出一个很好的例子或推理,以确定什么是最惯用的.与大多数社区相比,python倾向于强烈鼓励人们以某种方式做事,所以我希望这个问题及其答案即使不完全是黑白也会有用.
python ×6
constructor ×3
python-2.7 ×2
python-3.x ×2
arguments ×1
function ×1
inheritance ×1
oop ×1
overloading ×1
python-3.4 ×1
ruby ×1