Python就像JavaScript的继承一样 [英] Python like inheritance for JavaScript

查看:59
本文介绍了Python就像JavaScript的继承一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中我可以做这样的事情

In python I can do something like this

class MainClass:
    def __init__(self):
        self.name = "some_name"
    def startDoingStuff(self):
        print("I'm doing something boring")

    def printName(self):
        print("My name is " + self.name)



sub.py



sub.py

import main
class Sub(main.MainClass):
    def startDoingStuff(self):
        print("I'm doing something interesting")
        self.name = "sub"

sub = Sub()
sub.printName() # prints 'My name is some_name'
sub.startDoingStuff()
sub.printName() # prints 'My name is sub'

是否有等效的JavaScript?

Is there a JavaScript equivalent?

推荐答案

如果基于原型的继承有点令人生畏,你可以查看基于扩展的继承

If prototype-based inheritance is a little daunting, you might look into extension based inheritance.

一个非常基本的实现看起来像这样。 (上面链接的John Resig的实现更强大,但我认为这更具可读性,但具有相同的基本概念)

A really basic implementation looks like this. (John Resig's implementation linked above is more robust, but I think this is a little more readable, but with the same basic concept)

var extend = function(subTypeInit) {
    var SuperType = this;
    var SubType = function () {
         function SuperTypeProxy(args) {
              return SuperType.apply(this, args);
         }
         var base = new SuperTypeProxy(arguments);
         subTypeInit.apply(base, arguments);
         return base;
    }
    SubType.extend = extend.bind(SubType);
    return SubType;
}

然后可以像这样使用:

var Main = function (name) {
    var self = this;
    self.name = name;
    self.doSomething = function () {
         console.log("something boring");
    };
    self.printName = function () {
         console.log("Hi, I'm "+name);
    };
};

Main.extend = extend.bind(Main); //Manually attach to first parent.

var Sub = Main.extend(function () {
    var self = this;

    self.doSomething = function () {
         console.log("something interesting");
    };

    var superPrintName = self.printName;
    self.printName = function () {
         superPrintName();
         console.log("And I'm a sub class");
    };
});

var sub = new Sub("foo");
sub.doSomething(); //logs "something interesting"
sub.printName(); //logs "Hi, I'm foo" "And I'm a sub class"

一些请注意,你可能应该研究基于原型的继承,这正是javascript的真正构建。对于习惯于其他OO语言继承方法的人来说,基于扩展的继承更自然,但缺点是它以这种方式消耗更多资源来继承;你正在创建很多函数(以及很多闭包),它们可以真正加起来。

Some caveats here, you really probably should look into prototype based inheritance, which is what javascript is really built for. Extension-based inheritance is a little more natural for someone who's used to other OO languages' approaches to inheritance, but the disadvantage is that it consumes more resources to do inheritance this way; you're creating a lot of functions (and a lot of closures), which can really add up.

这篇关于Python就像JavaScript的继承一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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