Inyoka
Inyoka

Reputation: 1446

Python: nesting classes without complicating imports

Conceptual problem: I have a file called shape containing classes for lines, squares, rectangles etc like so ...

class Line:
    def __init__(self, length):
        self.length = length

class Square(Line):
    def __init__(self, length):
        super().__init__(length)

    def area(self):
        print(self.length * self.length)

Currently to create a Square shape I run :

mySquare = shape.Square(5) # 5 being the length of the sides.

'shape' refers to my file shape.py, and Square refers to the class Square within the file. If I nested Square within a class called Shape, would I then have to run :

$ square = shape.Shape.Square(5)

I want to create a Class Attribute for "shape" to list all the instances of shape. Is nesting the shapes withing a 'shape' class the correct way to accomplish this?

This is a mental stumbling block for me and would appreciate help in understanding the best way to approach this situation. It seems this would be a common problem as applications get more complex, especially when building API's whilst keeping naming and imports as simple as possible.

Upvotes: 1

Views: 63

Answers (1)

gelonida
gelonida

Reputation: 5630

Is this roughly what you're looking for:

import weakref

class Shape:
    all_shapes = []
    def __init__(self, *args, **kwargs):
        self.all_shapes.append(weakref.ref(self))

    @classmethod
    def get_all_shapes(cls):
        for wref in cls.all_shapes:
            shape = wref()
            if shape:
                yield shape

class Line(Shape):
    def __init__(self, length):
        super().__init__(length)
        self.length = length

class Square(Line):
    def __init__(self, length):
        super().__init__(length)

    def area(self):
        print(self.length * self.length)



l = Line(1)
l2 = Line(2)
print(list(Shape.get_all_shapes()))
del l
print(list(Shape.get_all_shapes()))
s = Square(5)
print(list(Shape.get_all_shapes()))

Upvotes: 2

Related Questions