Question 51
In Python, how is private attribute name mangling implemented for an attribute defined as self.__secret inside class Foo?
Name mangling transforms __attr to _ClassName__attr to prevent accidental name collisions in subclasses.
In Python, how is private attribute name mangling implemented for an attribute defined as self.__secret inside class Foo?
Name mangling transforms __attr to _ClassName__attr to prevent accidental name collisions in subclasses.
What is the output of the following code?
class Secret:
def __init__{self}:
self.__val = 42
def get_val(self):
return self.__vals = Secret()
print(getattr(s, '_Secret__val'))
Mangled attribute _Secret__val is accessible via getattr, returning 42.
What happens when attempting to access s.__val directly from outside class Secret where self.__val = 42?
Direct access to __val fails with AttributeError because the attribute name was mangled to _Secret__val.
Consider the code:
class Vector:
def __init__{self, x, y}:
self.x = x
self.y = y
def __len__{self}:
return int((self.x**2 + self.y**2)**0.5)$v = Vector(3, 4)
print(len(v))$
$len(v) calls v.__len__(), computing sqrt(3^2 + 4^2) = sqrt(25) = 5.$
Which dunder method must be implemented to make an instance callable like a function (e.g. obj())?
Defining __call__(self, *args, **kwargs) allows instances of the class to be called as functions.