3
I’ve seen in some scripts definitions of classes within other classes or functions like this:
class Grok(object):
class Foo(object):
...
...
What is the reason for this practice? It is only to not allow the direct instantiation of the class defined internally, and this is really a good practice or should I avoid its use at any cost ?
class Circle:
class DrawingAPIOne:
'''Implementation-specific abstraction'''
def drawCircle(self, x, y, radius):
print("API 1 is drawing a circle at ({}, {}) with radius {}".format(x, y, radius))
class DrawingAPITwo:
'''Implementation-specific abstraction'''
def drawCircle(self, x, y, radius):
print("API 2 is drawing a circle at ({}, {}) with radius {}".format(x, y, radius))
def __init__(self, x, y, radius):
'''Implementation-independent abstraction; Initialize the necessary attributes'''
self._x = x
self._y = y
self._radius = radius
def drawWithAPIOne(self):
'''Implementation-specific abstraction'''
objectOfAPIone = self.DrawingAPIOne()
objectOfAPIone.drawCircle(self._x, self._y, self._radius)
def drawWithAPITwo(self):
'''Implementation-specific abstraction'''
objectOfAPItwo = self.DrawingAPITwo()
objectOfAPItwo.drawCircle(self._x, self._y, self._radius)
def scale(self, percent):
'''Implementation-independent abstraction'''
self._radius *= percent
I saw this code on the website: https://www.djangospin.com/design-patterns-python/bridge/
"Essentially that’s right, you limit the use of that class to that scope and it can only be instantiated in there." Why start an answer with something that is usually 100% wrong? It’s Python - you don’t "limit scope" - the nested class is in a namespace of the outside class, but any code has access.
– jsbueno
@jsbueno Ok, for classes within class, and class within function?
– Maniero