【发布时间】:2021-02-17 13:48:39
【问题描述】:
A.pm
new {
my $_this = bless(+{}, __PACKAGE__);
$_this->{_native} = 1;
$_this->{_type} = 'cmd';
if ($this->{_type}) {
$class = 'A::B';
} else {
$class = 'A::C';
}
Class::Autouse->load($class);
$this = bless($_this, $class);
$this->new();
}
In side A/B.pm
use parent qw(A);
所以这里的 B 是从 A 派生的,但是当我调用 A->new(type = '') 时,B/C 的对象是根据传递的类型创建的。 谁能建议如何在 python 中实现这一点?
【问题讨论】:
-
$_this和$this有什么区别?你不应该在某处声明$this和my $this吗? -
您正在寻找的是工厂模式。谷歌“python 工厂模式”,你应该会找到各种实现。