
budman
User
Mar 30, 2012, 2:05 PM
Views: 7771
|
|
Re: [ChopperCharles] private and protected methods
|
|
|
Perl and Python != Java and C++ Python does recognize some things like private functions when the name starts with an underscore. However, it is not FULLY protected. Perl leaves private vars and methods to convention. To make a method work for either a passed ref, or a normal call, check if the first arg is a ref.
sub run { my $this = shift; if ( ref($this) ) { return $this->__foo(+shift) } else { return __foo($this) } } You can apply the same to __foo - check the first arg for ref, and then proceed.
sub __foo { my $this = shift; if ( ref($this) ) { unless ( (caller)[0]->isa( ref($this) ) ) { $this->lastError("Access to private method denied."); return -1; } } my $name = ref($this) ? shift : $this; print "Hello $name\n"; return 0; } Perl was never designed to be OO, it was band-aided to work with objects. Since objects are pretty much containers, this worked fine for most OOP concepts. Just like in C++, classes are pretty much structs with their inners kept private, unless you specify otherwise.
(This post was edited by budman on Mar 30, 2012, 2:22 PM)
|