L
L
leonidpetrosian2020-05-07 23:04:30
Python
leonidpetrosian, 2020-05-07 23:04:30

Why assign a class variable to itself?

Good afternoon, habravchane!

Recently I have been looking through different libraries and in many I meet this:

class Foo:
    boo = dict
    def __init__(self):
        self.boo = self.boo

Explain this structure to the negligent. An example may be detached from reality.
Real example of this implementation: https://github.com/networkx/networkx/blob/master/n...

Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2020-05-07
@leonidpetrosian

Alternatively, because boo is a class field. The line self.boo = self.boo assigns a field to an instance. I don't know why this might be necessary in practice, but here's an example to reproduce when it affects something:

class A:
    factory = dict
    
    def method(self):
        return self.factory()
    
    
a = A()
A.factory = list
print(a.method())  # []

class B:
    factory = dict
    
    def __init__(self):
        self.factory = self.factory
    
    def method(self):
        return self.factory()
    
    
b = B()
B.factory = list
print(b.method())  # всё равно словарь: {}

H
HemulGM, 2020-05-08
@HemulGM

Why assign a class variable to itself?

This makes no sense.
It makes sense if it's not just a variable, but a property. When an assignment can execute certain code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question