Is there any truncation for nested classes?

Recently, I saw several people doing similar things here in Stackoverflow:

class A:
    foo = 1

    class B:
        def blah(self):
            pass

In other words, they have nested classes. This works (although people new to Python seem to run into problems because they don't behave the way they thought), but I can't think of any reason to do this in any language whatsoever and, of course, not in Python . Is there such a truncation? Why do people do this? The search for this seems to him quite common in C ++, is there a good reason there?

+3
source share
8 answers

, , . ++ , .

+4

, , , , . Python, . , SomeClass OtherClass, - -, SomeClass.Reader OtherClass.Reader, SomeClassReader OtherClassReader.

++. . , , , CPP ( Qt - ). , "", , . , . , , .

, , Java. , ( ). , "" , .

+6

python, , . , Node List , , . Node Tree Graph. , / , . , , , List.Node , Node List, ListNode .

+3

, . ( . , , .;))

closure.

+2

Python ( lambdas), ++ 03 Java ( Java , ). , , . - :

Python:

(foo(x) if x.f == target else bar(x) for x in bazes)

++:

struct FooBar {
    Sommat operator()(const Baz &x) const {
        return (x.f == val) ? foo(x) : bar(x);
    }
    FooBar(int val) : val(val) {}
    int val;
};

vector<Sommat> v(bazes.size());
std::transform(bazes.begin(), bazes.end(), v.begin(), FooBar(target));

, ++ Java, - " , : , , , , ?" [*]

- , . Java , ++ TU, , , . , Java .

, ++. Python , ++ Java, - . , typedef , , , " ".

[*] : " for?", , ...

+2

++, , - . , :

class list
{
   public:

   class iterator 
   {
      // implementation code
   };

   class const_iterator
   {
      // implementation code
   };
};

++ - , node , ..

+1

" " , . , , .

  • / . , Java , . , Zen Python , , .

    import this

    Python , .

  • ( ). -, , , HTML.Node, HTML, , node. -, /, , , .

    Python, , , , , . Node, , node_factory = Node ( , ).

  • . Java ( ) . , , .

    Python decimal. , , . decimal . , . Python , Context decimal , context.Decimal('3') Decimal('3', context=context).

    Python, , , , isinstance __subclasscheck__ __instancecheck__. , - (, __init__). , , , Java , .

+1

Python . , , - , , , . , .

: "" , , . - . , , , .

def call_count(func):
    class Counter(object):
       def __init__(self):
           self.counter = 0
       def __repr__(self):
           return str(func)
       def __call__(self, *args, **kw):
           self.counter += 1
           return func(*args, **kw)
    return Counter()

:

>>> @call_count
... def noop(): pass
...
>>> noop()
>>> noop()
>>> noop.counter
2
>>> noop
<function noop at 0x7fc251b0b578>

, call_counter "Counter", , func , , , ( func) , , . .

0

Source: https://habr.com/ru/post/1781106/


All Articles