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中实现这一点吗?
发布于 2020-11-05 07:18:13
B/C的
对象是根据传入的类型创建的
new在Perl中没有什么特别之处,它只是一个普通的sub。没有什么能阻止您在Python中做同样的事情。
def new(cmd):
if type == 'cmd':
return A()
else:
return B()至于标题,
package MyClass {
sub new {
my ($class, $foo, $bar) = @_;
my $self = bless({}, $class);
$self->{foo} = $foo;
$self->{bar} = $bar;
return $self;
}
}
my $o = Class->new($foo, $bar);等同于
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def new(a_class, foo, bar):
return a_class(foo, bar)
o = MyClass.new(MyClass, foo, bar)
print(o.foo)但你通常会写下
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
o = MyClass(foo, bar)https://stackoverflow.com/questions/64687316
复制相似问题