прототип базирующимся по сравнению с основанным на классе наследованием

Правильный способ сделать это - использовать язык сценариев и библиотеку синтаксического анализа YAML для извлечения интересующего вас поля.

Вот пример того, как это сделать в Python. Если бы вы делали это по-настоящему, вы бы, вероятно, разбили его на несколько функций и получили бы лучшие отчеты об ошибках. Это буквально просто для иллюстрации некоторых трудностей, вызванных форматом calico.yaml, который объединяет несколько документов YAML, а не один. Вам также нужно перебрать некоторые из внутренних списков в документе, чтобы извлечь интересующее вас поле.

#!/usr/bin/env python3

import yaml

def foo():
    with open('/tmp/calico.yaml', 'r') as fil:
        docs = yaml.safe_load_all(fil)
        doc = None
        for candidate in docs:
            if candidate["kind"] == "DaemonSet":
                doc = candidate
                break
        else:
            raise ValueError("no YAML document of kind DaemonSet")
        l1 = doc["spec"]
        l2 = l1["template"]
        l3 = l2["spec"]
        l4 = l3["containers"]
        for containers_item in l4:
            l5 = containers_item["env"]
            env = l5
            for entry in env:
                if entry["name"] == "CALICO_IPV4POOL_CIDR":
                    return entry["value"]
    raise ValueError("no CALICO_IPV4POOL_CIDR entry")

print(foo())

Однако иногда вам нужно решение прямо сейчас , и сценарии оболочки очень хороши в этом.

Если вы работаете с конечной точкой API, то YAML, как правило, будет хорошо напечатан, поэтому вы можете с легкостью извлекать текст способами, которые не будут работать с произвольным YAML.

Что-то вроде следующего должно быть довольно устойчивым:

cat </tmp/calico.yaml | grep -A1 CALICO_IPV4POOL_CIDR | grep value: | cut -d: -f2 | tr -d ' "'

Хотя в конце стоит проверить с помощью регулярного выражения, что извлеченное значение действительно является действительной нотацией CIDR IPv4.

Ключевым моментом здесь является grep -A1 CALICO_IPV4POOL_CIDR.

Упомянутый вами двухэлементный словарь (показанный ниже) всегда будет отображаться как один фрагмент, так как это поддерево документа YAML.

    - name: CALICO_IPV4POOL_CIDR
      value: "192.168.0.0/16"

Ключи в calico.yaml не сортируются в алфавитном порядке в целом, но в конструкциях {"name": <something>, "value": <something else>}, name последовательно появляется до value.

197
задан Machavity 2 November 2018 в 02:41
поделиться

2 ответа

There are about a hundred terminology issues here, mostly built around someone (not you) trying to make their idea sound like The Best.

All object oriented languages need to be able to deal with several concepts:

  1. encapsulation of data along with associated operations on the data, variously known as data members and member functions, or as data and methods, among other things.
  2. inheritance, the ability to say that these objects are just like that other set of objects EXCEPT for these changes
  3. polymorphism ("many shapes") in which an object decides for itself what methods are to be run, so that you can depend on the language to route your requests correctly.

Now, as far as comparison:

First thing is the whole "class" vs "prototype" question. The idea originally began in Simula, where with a class-based method each class represented a set of objects that shared the same state space (read "possible values") and the same operations, thereby forming an equivalence class. If you look back at Smalltalk, since you can open a class and add methods, this is effectively the same as what you can do in Javascript.

Later OO languages wanted to be able to use static type checking, so we got the notion of a fixed class set at compile time. In the open-class version, you had more flexibility; in the newer version, you had the ability to check some kinds of correctness at the compiler that would otherwise have required testing.

In a "class-based" language, that copying happens at compile time. In a prototype language, the operations are stored in the prototype data structure, which is copied and modified at run time. Abstractly, though, a class is still the equivalence class of all objects that share the same state space and methods. When you add a method to the prototype, you're effectively making an element of a new equivalence class.

Now, why do that? primarily because it makes for a simple, logical, elegant mechanism at run time. now, to create a new object, or to create a new class, you simply have to perform a deep copy, copying all the data and the prototype data structure. You get inheritance and polymorphism more or less for free then: method lookup always consists of asking a dictionary for a method implementation by name.

The reason that ended up in Javascript/ECMA script is basically that when we were getting started with this 10 years ago, we were dealing with much less powerful computers and much less sophisticated browsers. Choosing the prototype-based method meant the interpreter could be very simple while preserving the desirable properties of object orientation.

195
ответ дан 23 November 2019 в 05:16
поделиться

You should check out a great book on JavaScript by Douglas Crockford. It provides a very good explanation of some of the design decisions taken by JavaScript creators.

One of the important design aspects of JavaScript is its prototypal inheritance system. Objects are first class citizens in JavaScript, so much that regular functions are also implemented as objects ('Function' object to be precise). In my opinion, when it was originally designed to run inside a browser, it was meant to be used to create lots of singleton objects. In browser DOM, you find that window, document etc all singleton objects. Also, JavaScript is loosely typed dynamic language (as opposed to say Python which is strongly typed, dynamic language), as a result, a concept of object extension was implemented through the use of 'prototype' property.

So I think there are some pros for prototype-based OO as implemented in JavaScript:

  1. Suitable in loosely typed environments, no need to define explicit types.
  2. Makes it incredibly easy to implement singleton pattern (compare JavaScript and Java in this regard, and you'll know what I am talking about).
  3. Provides ways of applying a method of an object in the context of a different object, adding and replacing methods dynamically from an object etc. (things which are not possible in a strongly typed languages).

Here are some of the cons of prototypal OO:

  1. No easy way of implementing private variables. Its possible to implement private vars using Crockford's wizardry using closures, but its definitely not as trivial as using private variables in say Java or C#.
  2. I don't know how to implement multiple inheritances (for what its worth) in JavaScript yet.
23
ответ дан 23 November 2019 в 05:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: