我无法找到明确的答案.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)
你说什么?还有另外一种方法吗?
我正在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)