Perl Moose parent class with child

package Point;
use Moose;

has 'x' => (isa => 'Int', is => 'rw');
has 'y' => (isa => 'Int', is => 'rw');

package Point3D;
use Moose;

extends 'Point';

has 'z' => (isa => 'Int', is => 'rw');

package main;

use Data::Dumper;

my $point1 = Point->new(x => 5, y => 7);
my $point3d = Point3D->new(z => -5);

$point3d = $point1;
print Dumper($point3d);

Is it possible to make a parent class a child, like C ++? In my example, $ point3d now Point, not Point3D, includes Point.

+3
source share
4 answers

Take a look at Class :: MOP documentation on CPAN , especially the methods clone_objectand rebless_instance:

sub to_3d {
  my ($self, %args) = @_;
  return Point3D->meta->rebless_instance(
    $self->meta->clone_object($self),
    %args,
  );
}

And then use it as below:

my $point_3d = $point->to_3d(z => 7);

It will also help process the newly defined %argsas if it were passed by the constructor. For instance. builders, default values, and type restrictions are considered during this assembly.

+5
source

Perl, . , , $point3d Point script. Point3D, Point3D. , "" . (, Perl, .)

+2

, Dumper , $point3d Point, Point3D, $point3d = $point1 $point3d , $point1, Point3D, $point3d, refcount 0, .

cdhowie, Perl , C/++. , , - non-OO , , Point3D::z($point1, 4), $point1 z-index 4, , z-index. , Point3D z [1] , , , Point3D , $point1 .

Point Point3D, bless ( , , Moose ), , rebempting Moose Moose. (, , , Moose . Moose, , .)

[1]... AUTOLOAD, .

+1

, , cdhowie . , , .

If you want to do $point3dthat contains a class object Pointin a real subclass object Point3D, the right way for OO to do this is to create a constructor new_from_Point()in the Point3Dclass that takes the class object Pointas input and creates the object Point3D(probably it should take an extra parameter "z"). A C ++ equivalent would be a constructor with a signature(const Point &, double &z=0.0)

0
source

Source: https://habr.com/ru/post/1783194/


All Articles