gpt4 book ai didi

python - 如何在 Go 中进行简单的继承

转载 作者:IT王子 更新时间:2023-10-29 00:50:27 25 4
gpt4 key购买 nike

我是一名 Python 开发人员,正在尝试学习 Go。目前我正在尝试重构我的第一个小项目,但我不太确定如何在结构之间共享方法。

长话短说,您将如何在 Go 中执行类似 Python 代码的操作?

class Super(object):

def CommonMethod(self):
print 'I am the common method.'


class One(Super):

def MethodOne(self):
self.CommonMethod()
print 'I am method one.'


class Two(Super):

def MethodTwo(self):
self.CommonMethod()
print 'I am method two.'

one = One()
one.MethodOne()

two = Two()
two.MethodTwo()

最佳答案

长话短说

在 Go 中,方法不仅仅像在 Python 或 Java 等其他语言中那样通过子类化神奇地继承。您可以定义接口(interface)并使用嵌入,但您必须为每种类型实现所需的方法。当然你可以直接从外部方法调用嵌入的方法,但是要注意任何变化都会发生在内部对象而不是外部对象上。

来自文档:

There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one. In our example, when the Read method of a bufio.ReadWriter is invoked, it has exactly the same effect as the forwarding method written out above; the receiver is the reader field of the ReadWriter, not the ReadWriter itself.

更多信息

以下是文档中的一些引用资料:

http://golang.org/doc/faq#Is_Go_an_object-oriented_language

Is Go an object-oriented language?

Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing.

因此,您可以拥有定义应在类型中实现的内容的接口(interface),但您必须为每种类型实现这些方法。

您拥有的一个便利是嵌入:

http://golang.org/doc/effective_go.html#embedding

Go does not provide the typical, type-driven notion of subclassing, but it does have the ability to “borrow” pieces of an implementation by embedding types within a struct or interface.

Interface embedding is very simple. We've mentioned the io.Reader and io.Writer interfaces before; here are their definitions.

type Reader interface {
Read(p []byte) (n int, err error)
}

type Writer interface {
Write(p []byte) (n int, err error)
}

The io package also exports several other interfaces that specify objects that can implement several such methods. For instance, there is io.ReadWriter, an interface containing both Read and Write. We could specify io.ReadWriter by listing the two methods explicitly, but it's easier and more evocative to embed the two interfaces to form the new one, like this:

// ReadWriter is the interface that combines the Reader and Writer interfaces.
type ReadWriter interface {
Reader
Writer
}

关于python - 如何在 Go 中进行简单的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26985191/

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