在Perl 6中继承私有属性 [英] Inheriting private attributes in Perl 6

查看:81
本文介绍了在Perl 6中继承私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文档中找不到任何内容,但是子类中似乎无法访问其超类的私有变量.我说的对吗?

I can't find anything in the docs, but it seems that there is no access in a subclass to its superclass's private variables. Am I right?

class A {
  has $!a;
}

class B is A {
  has $.b;

  method set_a($x) {
    $!a = $x;
  }
}

my $var = B.new();
$var.set_a(5);
say $var.a;

这会显示错误消息:

Attribute $!a not declared in class B

顺便说一句,在哪里可以阅读有关文档中的类的信息?我只找到了相当短的部分类和对象.

BTW where to read about Classes in the docs? I have only found a rather short section Classes and Objects.

推荐答案

在Perl 6中,只能在该类中访问在类中声明的属性.这意味着人们可以放心地重构类中的状态,而不必担心在类外使用该状态.

In Perl 6, an attribute declared in a class is accessible only within that class. This means one can confidently refactor the state in the class without having to worry about any uses of that state outside of the class.

子类在属性方面没有获得任何特殊的访问权限.某些语言提供了protected修饰符.根据设计,这在Perl 6中不存在.某些东西是该类的私有对象,或者是暴露于外界的(例如has $.a),因为:

Subclasses do not receive any special access with regards to attributes. Some languages provide a protected modifier. This does not exist in Perl 6, by design. Either something is private to that class, or is exposed (like has $.a) to the outside world, since:

  1. 就该类而言,子类是外部世界的一部分.
  2. 鉴于一般建议是优先考虑组成而不是继承",特权继承似乎很奇怪,或者提供了一种阻碍从继承到组成重构的机制.

相比之下,role中的

属性是组成类的,就像它们是在类本身中声明的一样.因此,可以在类主体中使用来自组成的role的属性.如果希望在OO上下文中编写可重用的功能,则更典型的是在Perl 6中使用角色和组合,而不是继承.实际上,将原始代码编写为:

Attributes in a role, by contrast, are composed into the class, working as if they had been declared in the class itself. Therefore, an attribute from a composed role may be used in the class body. If looking to write re-usable pieces of functionality in an OO context, it's more typical to use roles and composition in Perl 6, not inheritance. Indeed, writing the original code as:

role A {
  has $!a;
}

class B does A {
  has $.b;

  method set_a($x) {
    $!a = $x;
  }
  method a() { $!a }
}

my $var = B.new();
$var.set_a(5);
say $var.a;

根据需要工作.

这篇关于在Perl 6中继承私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆