J
John Machin
I have stumbled across some class definitions which include all/most
method names in a __slots__ "declaration". A cut-down and disguised
example appears at the end of this posting.
Never mind the __private_variables and the getter/setter approach, look
at the list of methods in the __slots__.
I note that all methods in an instance of a slotted class are read-only
irrespective of whether their names are included in __slots__ or not:
Given a = Adder(),
a.tally = 0
gets AttributeError: 'Adder' object attribute 'tally' is read-only
a.notinslots = 1
gets AttributeError: 'Adder' object attribute 'notinslots' is read-only
So is there some magic class-fu going down here, or is this just a
waste of memory space in the instances?
=== example ===
# class with method names in __slots__
class Adder(object):
__slots__ = [
# methods
'__init_',
'get_foo',
'get_value',
'set_foo',
'tally',
# private variables
'__foo',
'__value',
# public variables
'bar',
'zot',
]
def __init__(self, start=0):
self.__value = start
self.__foo = 666
self.bar = None
self.zot = 42
def tally(self, amount):
self.__value += amount
def get_value(self):
return self.__value
def set_foo(self, arg):
self.__foo = arg
def get_foo(self):
return self.__foo
def notinslots(self):
pass
=== end of example ===
method names in a __slots__ "declaration". A cut-down and disguised
example appears at the end of this posting.
Never mind the __private_variables and the getter/setter approach, look
at the list of methods in the __slots__.
I note that all methods in an instance of a slotted class are read-only
irrespective of whether their names are included in __slots__ or not:
Given a = Adder(),
a.tally = 0
gets AttributeError: 'Adder' object attribute 'tally' is read-only
a.notinslots = 1
gets AttributeError: 'Adder' object attribute 'notinslots' is read-only
So is there some magic class-fu going down here, or is this just a
waste of memory space in the instances?
=== example ===
# class with method names in __slots__
class Adder(object):
__slots__ = [
# methods
'__init_',
'get_foo',
'get_value',
'set_foo',
'tally',
# private variables
'__foo',
'__value',
# public variables
'bar',
'zot',
]
def __init__(self, start=0):
self.__value = start
self.__foo = 666
self.bar = None
self.zot = 42
def tally(self, amount):
self.__value += amount
def get_value(self):
return self.__value
def set_foo(self, arg):
self.__foo = arg
def get_foo(self):
return self.__foo
def notinslots(self):
pass
=== end of example ===