I am trying to achieve the following:
class A:
username = None
username = get_username()
def get_username(self):
if username is None:
try:
uname = os.environ["USER"]
except:
printf("Couldn't find a user name")
return uname
return username
Not sure how to achieve this. I’m sure I’m missing some “self.” prefixes but this is the first time I’m working with python and static members.
In a sense I want a class with some members and functions to calculate values for these members but I don’t want recalculations. I would also like these to be static functions and data members.
The problem is that the line “username = get_username()” the function hasn’t already been defined. If I put username after the function then it’s not
First, there’s no reason to assign
Nonetousernameif you’re just going to reassign it immediately after.Second, if you want the method to be a static method, you can’t give it a
selfargument. And if you want a real static method, you have to declare it explicitly.Otherwise, you need an instance of the class (that
self) to call it on, and you don’t have one yet.In Python 3, any regular method acts like a static method when called on the class, like an instance method when called on an instance. So, if you’re sure you’re never going to want to call
a.get_username()on an instancea, you can skip the decorator. But you still need to get rid of theselfparameter.I think what you’re actually trying to do is use a class variable to memoize the result of a static method. You can’t do that, but you can use a class variable to memoize the result of a class method, which may be close enough. That would look like this:
On the other hand, there’s no good reason username has to be a class member. You can memoize by adding a member to the function, by passing a mutable default variable, or in various other ways which don’t require infecting the class, and which allow you to leave
get_usernameas a static method instead of a class method.But really, the best solution is to find a memoization library on PyPI, in ActiveState’s recipe list, etc., so you can just write this:
Again, you can drop the
@staticmethodif you’re sure nobody’s ever going to try to create an instance ofAand callget_usernameon it.