Python 中一个类中具有相同名称的方法
如何在一个类中声明几个具有相同名称但具有不同数量的参数或不同类型的方法?
在接下来的课程中我必须改变什么?
class MyClass:
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
def my_method(self,parameter_A_that_Must_Be_String):
print parameter_A_that_Must_Be_String
def my_method(self,parameter_A_that_Must_Be_String,parameter_B_that_Must_Be_String):
print parameter_A_that_Must_Be_String
print parameter_B_that_Must_Be_String
def my_method(self,parameter_A_that_Must_Be_String,parameter_A_that_Must_Be_Int):
print parameter_A_that_Must_Be_String * parameter_A_that_Must_Be_Int
How can I declare a few methods with the same name, but with different numbers of parameters or different types in one class?
What must I change in the following class?
class MyClass:
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
def my_method(self,parameter_A_that_Must_Be_String):
print parameter_A_that_Must_Be_String
def my_method(self,parameter_A_that_Must_Be_String,parameter_B_that_Must_Be_String):
print parameter_A_that_Must_Be_String
print parameter_B_that_Must_Be_String
def my_method(self,parameter_A_that_Must_Be_String,parameter_A_that_Must_Be_Int):
print parameter_A_that_Must_Be_String * parameter_A_that_Must_Be_Int
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
使用Python 3.5或更高版本,您可以使用
@typing.overload
为重载函数/方法提供类型注释。来自文档:
Using Python 3.5 or higher, you can use
@typing.overload
to provide type annotations for overloaded functions/methods.From the docs:
简短的回答:你不能(请参阅之前的讨论)。通常您会使用类似的东西(您可以添加更多类型检查和重新排序):
Short answer: you can't (see this previous discussion). Typically you'd use something like (you could add more type checking and reorder):
从 Python 3.10 开始,更优雅的解决方案是使用 结构模式匹配。
As of Python 3.10 a more elegant solution would be to use Structural Pattern Matching.
这是行不通的。无论您有多少个参数,名称
m
都将被第二个m
方法覆盖。输出将很简单:
This cannot work. No matter how many arguments you have, the name
m
will be overriden with the secondm
method.The output will simple be:
您可以在Python中尝试多种方法:
http://www.artima.com/weblogs /viewpost.jsp?thread=101605
但我不认为多方法是一种可行的方法。相反,传递给方法的对象应该具有公共接口。您正在尝试实现类似于 C++ 中的方法重载,但在 Python 中很少需要。实现此目的的一种方法是使用
isinstance
级联ifs
,但这很丑陋。You can try multimethods in Python:
http://www.artima.com/weblogs/viewpost.jsp?thread=101605
But I don't believe multimethod is a way to go. Rather objects that you pass to a method should have common interface. You are trying to achieve method overloading similar to the one in C++, but it is very rarely required in Python. One way to do this is a cascade of
ifs
usingisinstance
, but that's ugly.Python 与 Java 完全不同。
没有真正的类型,只有带有方法的对象。
有一种方法可以测试传递的对象是否来自类,但这主要是不好的做法。
但是,您想要为前两个方法生成的代码应该类似于
第三个方法,那么...使用不同的名称...
Python is nothing like Java.
There are not really types, just objects with methods.
There is a way to test if a passed object is from a class, but it is mainly bad practices.
However, the code you want to produce for the two first methods should be something like
For the third, well... Use a different name...
您可能需要类似于以下的模式:
请注意,在方法名称的开头添加“_”是标记私有方法的约定。
You probably want a pattern similar to the following:
Note that adding '_' to the beginning of a method name is convention for marking a private method.
我认为所有答案中都缺少一个非常简单的例子,那就是:当方法变体之间的唯一区别是参数数量时该怎么办。答案仍然是使用参数数量可变的方法。
假设您从一个需要使用两个参数的方法开始
,然后您需要添加一个仅包含第二个参数的变体(例如,因为整数是多余的),解决方案非常简单:
这个解决方案的好处是没有无论调用代码之前使用关键字参数还是位置参数,它仍然会继续工作。
I think one very simple example is missing from all the answers, and that is: what to do when the only difference between variations on the method is the number of arguments. The answer still is to use a method with variable number of arguments.
Say, you start with a method that requires use of two arguments
then you need to add a variant with just the second argument (say, because the integer is redundant), the solution is very simple:
The nice thing about this solution is that no matter if the calling code used keyword arguments or positional arguments before, it will still continue to work.
我认为 @overload 解决了这个问题:VS Code ->
open()
上的 f12 ->它显示了open()
函数的一堆重复项:所以,这就是结果......
抱歉我有点紧张......
I think
@overload
solves the thing: VS Code -> f12 onopen()
-> it shows a bunch of duplicates of theopen()
function:So, here's the result...
I'm sorry for being nervous...
您可以使用
multipledispatch.dispatch
和typing.overload
优雅地完成此操作,而不是使用丑陋的isinstance(b, str)
或*参数
。安装:
pip3 install multipledispatch
你得到:
使用@overload,你将看到输入选项的提示:
和
没有@overload,它仍然有效,但没有提示:
You can use
multipledispatch.dispatch
andtyping.overload
to do that ellegantly instead of using uglyisinstance(b, str)
or*args
.Install:
pip3 install multipledispatch
You get:
With @overload, you will see the hints of input options:
and
Without @overload, it still works, but no hints:
您可以拥有一个接受可变数量参数的函数。
所以你可以修改你的函数如下:
You can have a function that takes in a variable number of arguments.
So you can modify your function as follows:
你不能。没有重载或多重方法或类似的东西。一个名字指的是一件事。无论如何,就语言而言,您始终可以自己模拟它们...您可以使用
isinstance
检查类型(但请正确执行 - 例如在Python 2中,使用basestring
来检测字符串和 unicode),但它很丑陋,通常不鼓励并且很少有用。如果这些方法执行不同的操作,请为它们指定不同的名称。还要考虑多态性。You can't. There are not overloads or multimethods or similar things. One name refers to one thing. As far as the language is concerned anyway, you can always emulate them yourself... You could check types with
isinstance
(but please do it properly - e.g. in Python 2, usebasestring
to detect both strings and unicode), but it's ugly, generally discouraged and rarely useful. If the methods do different things, give them different names. Consider polymorphism as well.