简体   繁体   English

Python就像JavaScript的继承一样

[英]Python like inheritance for JavaScript

In python I can do something like this 在python中我可以做这样的事情

main.py main.py

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'

Is there a JavaScript equivalent? 是否有JavaScript等价物?

If prototype-based inheritance is a little daunting, you might look into extension based inheritance . 如果基于原型的继承有点令人生畏,您可能会考虑基于扩展的继承

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) (上面链接的John Resig的实现更强大,但我认为这更具可读性,但具有相同的基本概念)

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;
}

Then it can be used like this: 然后它可以像这样使用:

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"

Some caveats here, you really probably should look into prototype based inheritance, which is what javascript is really built for. 这里有一些警告,你真的可能应该研究基于原型的继承,这正是javascript的真正构建。 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; 对于习惯于其他OO语言继承方法的人来说,基于扩展的继承更自然,但缺点是它以这种方式消耗更多资源来继承; you're creating a lot of functions (and a lot of closures), which can really add up. 你正在创建很多函数(以及很多闭包),这些函数可以真正加起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM