gpt4 book ai didi

ruby - 继承但不与父类(super class)共享,不共享命名空间的变量/常量

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:23 25 4
gpt4 key购买 nike

有没有办法引入一些具有以下三个属性的变量/常量?

a) It inherits a superclass's value when it is not assigned in the own class.

b) It does not inherit other classes's value other than for superclasses's (even if they share the namespace).

c) It does not overwrite the superclasses's value when assigned in the own class.

使用类实例变量,a)不满足。

class A; @foo = :foo end
class B < A; @foo end # => nil (Does not satisfy (a))
class A; class C; @foo end end # => nil (Satisfies (b))

class B < A; @foo = :bar end
class A; @foo end # => :foo (Satisfies (c))

使用类变量,c)不满足。

class A; @@foo = :foo end
class B < A; @@foo end # => :foo (Satisfies (a))
class A; class C; @foo end end # => NameError (Satisfies (b))

class B < A; @@foo = :bar end
class A; @foo end # => :bar (Does not satisfy (c))

使用常量,b)不满足。

class A; Foo = :foo end
class B < A; Foo end # => :foo (Satisfies (a))
class A; class C; Foo end end # => :foo (Does not satisfy (b))

class B < A; Foo = :bar end
class A; Foo end # => :foo (Satisfies (c))

我想要这样的东西:

class A; something = :foo end
class B < A; something end # => :foo (Satisfies (a))
class A; class C; something end end # => nil or Error (Satisfies (b))

class B < A; something = :bar end
class A; something end # => :foo (Satisfies (c))

如果不能简单地通过分配和引用变量/常量来完成,那么有没有办法实现具有此属性的访问器方法?

最佳答案

您需要创建您自己的具有所需特定属性的访问器。例如,

module InheritableProperty
def property
@property || superclass.property
end
def property=(value)
@property = value
end
end

class A
extend InheritableProperty
end
class B < A
extend InheritableProperty
class C
extend InheritableProperty
end
end

A.property = 1
A.property # => 1
B.property # => 1
B::C.property # error

A.property = 1
B.property = 2
A.property # => 1
B.property # => 2
B::C.property # error

A.property = 1
B.property = 2
B::C.property = 3
A.property # => 1
B.property # => 2
B::C.property # => 3

关于ruby - 继承但不与父类(super class)共享,不共享命名空间的变量/常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543355/

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