Hi nevdka,
..But that means having a subclass, which is what I want to avoid. Is there a better way to set common attributes?..
As it has previously been said, doing a subclass of the class "Car" would have been the way to go, however, if the only thing that changes is the "type" of car, i.e Toyota, kia, Ford are what is changing then one can just provision that into a generic class of Car like so:
use warnings; use strict; { # begin of Car class package Car; sub new { my $class = shift; my $self = {}; bless $self, $class; $self->_init(@_); return $self; } { my @_init_data = qw(name drive body engine_cap); sub _init { my ( $self, $description ) = @_; my %data; @data{@_init_data} = @$description{@_init_data}; %$self = %data; } } sub car_name { my $self = shift; return $self->{name}; }
sub drive_type { my ( $self, $drive ) = @_; if ($drive) { unless ( $drive =~ /^(?:fwd|rwd|4wd)$/ ) { die "$drive not a valid drive type. Use fwd, rwd or 4w +d\n"; } $self->{'drive'} = $drive; } return $self->{'drive'}; } sub body_type { my ( $self, $body ) = @_; if ($body) { unless ( $body =~ /^(?:sedan|wagon|coupe|hatch)$/ ) { die "$body not a valid body type. Use sedan, wagon, coupe or hatch\n"; } $self->{'body'} = $body; } return $self->{'body'}; } sub engine_cap { my ( $self, $cap ) = @_; if ($cap) { $self->{'engine_cap'} = $cap; } return $self->{'engine_cap'}; }
If I may also advise, please look into A postmodern object system for Perl 5 like Moose or Moo, instead of this intrinsic Perl OOP} # end of Car class my $car = Car->new( { name => 'Toyota', drive => '4wd', body => 'wagon', engine_cap => + 2010 } ); print join " " => $car->car_name, $car->drive_type, $car->body_type, $car->engine_cap; print $/; $car = Car->new( { name => 'Kia', drive => 'fwd', body => 'sedan', engine_cap => 20 +08 } ); print join " " => $car->car_name, $car->drive_type, $car->body_type, $car->engine_cap;
In reply to Re: Setting common object attributes
by 2teez
in thread Setting common object attributes
by nevdka
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |