[英]Equivalent of perl bless in python
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中實現這一點?
B/C 的對象是根據傳遞的類型創建的
Perl 中的new
沒有什么特別之處。 這只是一個普通的潛艇。 沒有什么能阻止你在 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.