Created
February 9, 2012 20:07
-
-
Save draegtun/1782691 to your computer and use it in GitHub Desktop.
Python accessor example converted to Moose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
package AnotherPerson; | |
use Moose; | |
use namespace::autoclean; | |
has _firstname => (is => 'rw', isa => 'Str', accessor => 'firstname'); | |
has _lastname => (is => 'rw', isa => 'Str', accessor => 'lastname' ); | |
} | |
my $you = AnotherPerson->new; | |
$you->firstname('David'); | |
$you->lastname('Mertens'); | |
# | |
# Stackoverflow answer: http://stackoverflow.com/a/9187853/12195 | |
# | |
__END__ | |
# orig Python example | |
class AnotherPerson: | |
def __init__(self): | |
self._firstname = None | |
self._lastname = None | |
@property | |
def firstname(self): | |
return self._firstname | |
@firstname.setter | |
def firstname(self, newname): | |
self._firstname = newname | |
@property | |
def lastname(self): | |
return self._lastname | |
@lastname.setter | |
def lastname(self, newname): | |
self._lastname = newname | |
you = AnotherPerson() | |
you.firstname = 'David' # These two lines call instance methods | |
you.lastname = 'Mertens' |
Alright, see this gist: https://gist.github.com/1790290
There are some Perl modules already on CPAN which do provide lvalue accessors.....
- https://metacpan.org/module/Object::Accessor
- https://metacpan.org/module/Class::Accessor::Lvalue
- https://metacpan.org/module/Object::props
- https://metacpan.org/module/methods
I've never tried any of these so YMMV.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No, wait, even better, just use Want: https://metacpan.org/module/Want