【问题标题】:Equivalent of perl bless in pythonpython中perl bless的等价物
【发布时间】: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 中实现这一点?

【问题讨论】:

标签: python perl


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多