相关疑难解决方法(0)

什么是在Python中拥有多个构造函数的干净,pythonic方式?

我无法找到明确的答案.AFAIK,你不能__init__在Python类中拥有多个函数.那么我该如何解决这个问题呢?

假设我有一个Cheese使用该number_of_holes属性调用的类.我怎样才能有两种创建奶酪对象的方法......

  1. 一个像这样的洞: parmesan = Cheese(num_holes = 15)
  2. 并且不带参数并且只是随机化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)

你说什么?还有另外一种方法吗?

python constructor

660
推荐指数
9
解决办法
26万
查看次数

python中不同参数类型的方法重载

我正在python中编写一个预处理器,其中一部分与AST一起工作.

有一种render()方法可以将各种语句转换为源代码.

现在,我有这样的(缩短):

def render(self, s):
    """ Render a statement by type. """

    # code block (used in structures)
    if isinstance(s, S_Block):
        # delegate to private method that does the work
        return self._render_block(s)

    # empty statement
    if isinstance(s, S_Empty):
        return self._render_empty(s)

    # a function declaration
    if isinstance(s, S_Function):
        return self._render_function(s)

    # ...
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它很乏味,容易出错并且代码很长(我有更多种类的语句).

理想的解决方案是(在Java语法中):

String render(S_Block s)
{
    // render block
}

String render(S_Empty s)
{
    // render empty statement
}

String render(S_Function s)
{
    // render function …
Run Code Online (Sandbox Code Playgroud)

python oop design-patterns

18
推荐指数
3
解决办法
7141
查看次数

标签 统计

python ×2

constructor ×1

design-patterns ×1

oop ×1