Serving the Quantitative Finance Community

 
User avatar
Piyushbhatt
Topic Author
Posts: 5
Joined: July 8th, 2022, 5:14 am

Why can't slots be used alongside decorators in Python to guarantee encapsulation?

November 7th, 2022, 11:08 am

According to what I've read, Python does not strictly enforce Encapsulation from here. As shown below, slots are commonly utilised for quicker attribute access and memory savings. However, encapsulation may be strongly maintained using slots and decorators, as seen in the following code:
class GetSet(object):

__slots__ = ["attrval"]
def __init__(self,value):
    self.attrval = value

@property
def var(self):
    #print 'getting the "var" attribute'
    return self.attrval

@var.setter
def var(self,value):
    #print 'setting the "var" attribute'
    self.attrval = value

@var.deleter
def var(self):
    #print 'deleting the "var" attribute'
    self.attrval = None
An instance of GetSet will not have dynamic variable settings (due to slots), and the setter and getter methods will call the class's method definitions. Isn't encapsulation completely invoked?
Hi, I’m Piyush. I’m a Computer Science and Engineering graduate who is passionate about programming and technology. I found this forum in hopes of learning something valuable in programming.
 
User avatar
tags
Posts: 3162
Joined: February 21st, 2010, 12:58 pm

Re: Why can't slots be used alongside decorators in Python to guarantee encapsulation?

November 8th, 2022, 8:43 pm

I don't understand your question to be honest.
Can you please show what your code returns and also what you were expecting? 
 
User avatar
Cuchulainn
Posts: 20252
Joined: July 16th, 2004, 7:38 am
Location: 20, 000

Re: Why can't slots be used alongside decorators in Python to guarantee encapsulation?

November 9th, 2022, 4:24 pm

OOP in Python is a bit of a horror story at the best of times. Any tricks is making a silk purse from a sow's lug.