繁体   English   中英

相当于python中的perl bless

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM