gpt4 book ai didi

perl - Perl 中的对象和类有什么区别?

转载 作者:行者123 更新时间:2023-12-01 23:20:36 24 4
gpt4 key购买 nike

我在理解对象和类之间的概念差异时遇到了一些麻烦。我不太了解任何编程语言中两者之间的区别,但目前我正在使用 Perl 和 Moose,所以我更喜欢使用这些东西进行解释。

干杯

最佳答案

有很多“类是蓝图,对象是根据该蓝图构建的东西”,但是由于您要求使用 Moose 和 Perl 提供特定示例,因此我想我会提供一个。

在以下示例中,我们将创建一个名为“Hacker”的类。这个类(就像一个蓝图)描述了黑客是什么(他们的属性)以及他们可以做什么(他们的方法):

package Hacker;       # Perl 5 spells 'class' as 'package'

use Moose; # Also enables strict and warnings;

# Attributes in Moose are declared with 'has'. So a hacker
# 'has' a given_name, a surname, a login name (which they can't change)
# and a list of languages they know.

has 'given_name' => (is => 'rw', isa => 'Str');
has 'surname' => (is => 'rw', isa => 'Str');
has 'login' => (is => 'ro', isa => 'Str');
has 'languages' => (is => 'rw', isa => 'ArrayRef[Str]');

# Methods are what a hacker can *do*, and are declared in basic Moose
# with subroutine declarations.

# As a simple method, hackers can return their full name when asked.

sub full_name {
my ($self) = @_; # $self is my specific hacker.

# Attributes in Moose are automatically given 'accessor' methods, so
# it's easy to query what they are for a specific ($self) hacker.

return join(" ", $self->given_name, $self->surname);
}

# Hackers can also say hello.

sub say_hello {
my ($self) = @_;

print "Hello, my name is ", $self->full_name, "\n";

return;
}

# Hackers can say which languages they like best.

sub praise_languages {
my ($self) = @_;

my $languages = $self->languages;

print "I enjoy programming in: @$languages\n";

return;
}

1; # Perl likes files to end in a true value for historical reasons.

现在我们已经有了 Hacker 类,我们可以开始制作 Hacker 对象:
#!/usr/bin/perl
use strict;
use warnings;
use autodie;

use Hacker; # Assuming the above is in Hacker.pm

# $pjf is a Hacker object

my $pjf = Hacker->new(
given_name => "Paul",
surname => "Fenwick",
login => "pjf",
languages => [ qw( Perl C JavaScript) ],
);

# So is $jarich

my $jarich = Hacker->new(
given_name => "Jacinta",
surname => "Richardson",
login => "jarich",
languages => [ qw( Perl C Haskell ) ],
);

# $pjf can introduce themselves.

$pjf->say_hello;
$pjf->praise_languages;

print "\n----\n\n";

# So can $jarich

$jarich->say_hello;
$jarich->praise_languages;

这导致以下输出:
Hello, my name is Paul Fenwick
I enjoy programming in: Perl C JavaScript

----

Hello, my name is Jacinta Richardson
I enjoy programming in: Perl C Haskell

如果我愿意,我可以拥有任意数量的 Hacker 对象,但仍然只有一个 Hacker 类描述了所有这些是如何工作的。

祝一切顺利,

保罗

关于perl - Perl 中的对象和类有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/448657/

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