duandie5707 2015-11-18 15:04
浏览 11
已采纳

如何在父方法中调用子方法? [重复]

This question already has an answer here:

package main

import "fmt"

type Super struct{}

func (super *Super) name() string {
    return "Super"
}

func (super *Super) WhoAmI() {
    fmt.Printf("I'm %s.
", super.name())
}

type Sub struct {
    Super
}

func (sub *Sub) name() string {
    return "Sub"
}

func main() {
    sub := &Sub{Super{}}
    sub.WhoAmI()
}

I want to get "I'm Sub", but I get "I'm Super" instead.

I already know sub.WhoAmI will call sub.Super.WhoAmI, but I still want to know if there is a way to get "I'm Sub". In Python when I write following code:

class Super(object):

    def name(self):
        return "Super"

    def WhoAmI(self):
        print("I'm {name}".format(name=self.name()))

class Sub(Super):

    def name(self):
        return "Sub"


if __name__ == "__main__":
    sub  = Sub()
    sub.WhoAmI()

I can get "I'm Sub".

</div>
  • 写回答

2条回答 默认 最新

  • dpikoto468637 2015-11-18 15:39
    关注

    Embedding is not subclassing. There are no superclasses or subclasses in Go. Sub here is not a "child" of Super. It contains a Super. You can't do you're trying to do. You need to organize your code in a different way so that it's not needed.

    For example, here (playground) is a more natural way to do this in Go:

    package main
    
    import "fmt"
    
    type Namer interface {
        Name() string
    }
    
    type Super struct{}
    
    func (sub *Super) Name() string {
        return "Super"
    }
    
    type Sub struct{}
    
    func (sub *Sub) Name() string {
        return "Sub"
    }
    
    func WhoAmI(namer Namer) {
        fmt.Printf("I'm %s.
    ", namer.Name())
    }
    
    func main() {
        sub := &Sub{}
        WhoAmI(sub)
    }
    

    Rather than focus on classes (which Go doesn't have), this focuses on interfaces. It's not a question of what things are, it's a question of what they can do. This is a very powerful approach to programming, and in practice is often much more flexible and less error-prone than inheritance abstractions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?