C++ python中的方法重载

发布于 2024-09-14 01:57:37 字数 459 浏览 8 评论 0原文

假设一个C++类有几个构造函数,它们根据各自参数的数量、类型和顺序进行重载,例如,constructor(int x, int y)和constructor(float x, float y, float z),我觉得这两个都是重载方法,用哪一个就看参数了,对吧?那么在 python 中,我怎样才能创建一个可以像这样工作的构造函数呢?我注意到 python 有 def 方法(self, *args, **kwargs):,所以我可以像这样使用它: def __init__(self, *args),然后我检查*args的长度,如if len(args) == 2:,然后根据2参数构造函数进行构造,if len( args) == 3,然后使用 3 参数构造函数等。那么,这行得通吗?或者有没有更好的方法用python来做?或者我应该以其他方式思考可以利用 python 功能本身的优势?谢谢~

suppose a C++ class has several constructors which are overloaded according the number and type and sequences of their respective parameters, for example, constructor(int x, int y) and constructor(float x, float y, float z), I think these two are overloaded methods, which one to use depends on the parameters, right? So then in python, how could I create a constructor that can work like this? I notice that python has the def method(self, *args, **kwargs):, so can I use it like: def __init__(self, *args), then I check the length of *args, like if len(args) == 2:, then construct according to the 2-parameters constructor, if len(args) == 3, then use the 3-parameters constructor, etc. So, does that work? Or is there any better way to do it with python? Or should I think in other ways that could take the advantage of python feature itself? thanks~

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

左耳近心 2024-09-21 01:57:37

通常,您可以对

  • 稍微改变的设计
  • 默认参数(def __init__(self, x = 0.0, y = 0.0, z = 0.0)
  • 使用多态性(在鸭子类型中)进行任意 组合。语言中,如果 SomeThing 和 SomeSlightlyDifferentThing 都不从另一个继承,则不需要重载,只要它们的接口足够相似)。

如果这看起来不可行,请加倍努力;)如果它仍然不可行,请查看大卫的链接。

Usually, you're fine with any combination of

  • slightly altered design
  • default arguments (def __init__(self, x = 0.0, y = 0.0, z = 0.0))
  • use of polymorphism (in a duck-typed language, you don't need an overload for SomeThing vs SomeSlightlyDifferentThing if neither inherits from the other one, as long as their interfaces are similar enough).

If that doesn't seem feasible, try harder ;) If it still doesn't seem feasible, look at David's link.

农村范ル 2024-09-21 01:57:37

这实际上取决于你想做什么。 *args/**kwargs 方法工作得相当好,delnan 建议的默认参数也是如此。

在这种情况下,C++ 和 Python 之间的主要区别在于您尝试执行的操作的内容原因。如果您有一个需要浮点数的类,只需尝试将参数转换为浮点数。您还可以依靠默认参数来分支您的逻辑:

class Point(object):
    def __init__(self, x=0.0, y=0.0, z=None):
        # Because None is a singleton, 
        # it's like Highlander - there can be only one! So use 'is'
        # for identity comparison
        if z is None:
            self.x = int(x)
            self.y = int(y)
            self.z = None
        else:
            self.x = float(x)
            self.y = float(y)
            self.z = float(z)

p1 = Point(3, 5)
p2 = Point(1.0, 3.3, 4.2)
p3 = Point('3', '4', '5')
points = [p1, p2, p3]
for p in points:
    print p.x, p.y, p.z

当然,您不必分配 self.z = None ,这只是为了方便我的示例。

有关使用哪种模式的最佳建议,

在[17]中:导入这个
Python 之禅,作者:Tim Peters

美丽总比丑陋好。
显式优于隐式。
简单胜于复杂。
...

如果您的模式美观、明确且简单,那么它可能就是正确的选择。

It really depends on what you want to do. The *args/**kwargs method works fairly well, as does the default arguments that delnan suggests.

The main difference between C++ and Python in this case is the what and why of what you are trying to do. If you have a class that needs floats, just try casting the arguments as floats. You can also rely on default arguments to branch your logic:

class Point(object):
    def __init__(self, x=0.0, y=0.0, z=None):
        # Because None is a singleton, 
        # it's like Highlander - there can be only one! So use 'is'
        # for identity comparison
        if z is None:
            self.x = int(x)
            self.y = int(y)
            self.z = None
        else:
            self.x = float(x)
            self.y = float(y)
            self.z = float(z)

p1 = Point(3, 5)
p2 = Point(1.0, 3.3, 4.2)
p3 = Point('3', '4', '5')
points = [p1, p2, p3]
for p in points:
    print p.x, p.y, p.z

You don't, of course, have to assign self.z = None, that was simply for the convenience of my example.

For the best advice about which pattern to use,

In [17]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
...

If your pattern is beautiful, explicit, and simple, it just may be the right one to use.

岁月苍老的讽刺 2024-09-21 01:57:37
I think these two are overloaded methods, which one to use depends on the parameters, right? 

抱歉,如果我看起来很挑剔,但只是想清楚地表明这种差异。

术语“形参”和“自变量”在 C++

参数中具有非常具体的含义:函数调用表达式中以逗号分隔的列表中以括号为界的表达式、函数中以逗号分隔的列表中以括号为界的预处理标记序列 -例如宏调用、 throw 的操作数或模板实例化中由尖括号包围的逗号分隔列表中的表达式、类型 ID 或模板名称。也称为实际参数或实际参数。

参数:作为函数声明或定义的一部分声明的对象或引用,或者在异常处理程序的 catch 子句中声明的对象或引用,它在进入函数或处理程序时获取值;类似函数的宏定义中紧跟在宏名称后面的括号包围的逗号分隔列表中的标识符;或模板参数。参数也称为形式参数或形式参数

I think these two are overloaded methods, which one to use depends on the parameters, right? 

Sorry, if I seem to be nitpicking, but just thought of bringing this difference out clearly.

The term parameters and arguments have very specific meaning in C++

argument: an expression in the comma-separated list bounded by the parentheses in a function call expression, a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation, the operand of throw, or an expression, type-id or template-name in the commaseparated list bounded by the angle brackets in a template instantiation. Also known as an actual argument or actual parameter.

parameter: an object or reference declared as part of a function declaration or definition, or in the catch clause of an exception handler, that acquires a value on entry to the function or handler; an identifier from the commaseparated list bounded by the parentheses immediately following the macro name in a function-like macro definition; or a template-parameter. Parameters are also known as formal arguments or formal parameters

一影成城 2024-09-21 01:57:37

本文讨论如何在 Python 中创建多方法装饰器。我还没有尝试过他们提供的代码,但它定义的语法看起来相当不错。这是文章中的一个示例:

from mm import multimethod

@multimethod(int, int)
def foo(a, b):
    ...code for two ints...

@multimethod(float, float):
def foo(a, b):
    ...code for two floats...

@multimethod(str, str):
def foo(a, b):
    ...code for two strings...

This article talks about how a multimethod decorator can be created in Python. I haven't tried out the code that they give, but the syntax that it defines looks quite nice. Here's an example from the article:

from mm import multimethod

@multimethod(int, int)
def foo(a, b):
    ...code for two ints...

@multimethod(float, float):
def foo(a, b):
    ...code for two floats...

@multimethod(str, str):
def foo(a, b):
    ...code for two strings...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文