this is probably a super nub question, apologies. I'm trying to achieve an effect in Python I am familiar with from PHP, which is building getter and setter functions for private attributes.
In PHP I will commonly do something like this:
<?php
class newClass() {
private $var = null;
function newClass($initVal) {
//init
}
public function get($var) {
if ( isset($this->$var) ) {
return $this->$var;
}
}
}
?>
But, trying the same idea in Python:
class newClass():
def __init__(self, initVal):
self.__nameOfVar1 = initVal
self.__nameOfVar2 = initVal
def get(self, var):
#assuming, when called, var = nameOfVar1
if self.__var:
return self.__var
Throws an error AttributeError:'newClass' object has no attribute '__var'
And quite rightly so, it doesn't. How do I build getter and setter functions to access private attributes?
UPDATE:
I've left the original question because it seems useful for new comers to Python to learn which conventions from other languages they might accidentally be bringing forward. But in reality, my initial problem was a bit different, in attempting to make the problem more general I obfuscated my actual need. So here's an amendment:
In fact I was not working with private attributes; in fact, I am dealing with trying to pass an attribute downward through a composition circumstance. ie:
Class A
, as an attribute, has a Class B
object that does not inherit from Class A
. It is almost never the case that Class B
needs any information from Class A
, but in my project there is one circumstance where, if a user chooses not provide information to Class B
, there is a statement that makes a last-ditch attempt to infer a reasonable solution, but it requires information from Class A
that, normally, it never needs.
I could build Class B
to always have had that information, but that means that almost always I'm just wasting that time and memory (trivial though it might be). To make this concrete, imagine this:
toothbrush
has bristles
, and bristles
can, provided the user supplies a preferred brushing experience, create a number of bristles appropriate to either a "soft" or a "firm" brush. But, if the user doesn't provide this, then I'd like bristles
to ask brush
for it's surface area, allowing it to guess what an average number should be.
I came up with this, though I have the intuitive sense that Python programmers will hate me for it; I'd just like to understand why:
@staticmethod
def request(self, var):
appIndex = self.__dict__
if appIndex[var]:
return appIndex[var]
print Class.request(instance, var)
Works like a charm, but I think this is Python heresy. Why?