gpt4 book ai didi

perl - 如何在面向对象的 Perl 中定义私有(private)或内部方法?

转载 作者:行者123 更新时间:2023-12-02 07:41:20 34 4
gpt4 key购买 nike

我正在使用达米安康威的“由内而外”的物体,正如他精彩的书所描述的那样Perl Best Practices在我的客户处构建一个面向对象的安全系统接口(interface)。我遇到需要在我的模块中使用内部辅助方法,我通常将其指定为“_some_method”。然而,这似乎破坏了封装,因为它们可以通过包名称直接调用。有没有办法让这些方法真正私有(private)化?举个例子,

use SOD::MyOOInterface;

my $instance1 = SOD::MyOOInterface->new();
$instance1->_some_method; #this produces an error:
SOD::MyOOInterface::_some_method; # this results in a
# successful method call

显然我不希望直接调用 _some_method 成功。有什么办法可以保证这一点吗?

最佳答案

package Foo;

## declare inside-out hashes here:

my %attr_a;
my %attr_b;

## declare private methods here

my $private_1 = sub {
my $self = shift;
# can use $attr_a{$self} here...
...
};

my $private_2 = sub {
my $self = shift;
...
};

## public methods here

sub new { ... }

sub public_1 {
my $self = shift;
# can access attributes here
# can call private methods too, with slightly odd syntax:
my $result = $self->$private_1(@args);
...
}

1;

关于perl - 如何在面向对象的 Perl 中定义私有(private)或内部方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1734385/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com