[Tutor] Good approach regarding classes attributes

Peter Otten __peter__ at web.de
Tue Sep 9 00:09:23 CEST 2014


Juan Christian wrote:

>>
>> > On Mon, Sep 8, 2014 at 5:58 AM, Peter Otten <__peter__ at web.de> wrote:
>>
>> In that spirit here's an alternative implementation of the User class:
>>
>> from collections import namedtuple
>> User = namedtuple(
>>     "User",
>>     "steamid personaname lastlogoff profileurl "
>>     "avatar timecreated countrycode")
>>
>> You may note that I refrained from making little improvements to the
>> attribute names -- another odd preference of mine ;) -- which also helps
>> simplify the fetch_users() implementation:
>>
>> ...
>> for user in user_list:
>>     if user["communityvisibilitystate"] == 3:
>>         users.append(User._make(user[field] for field in User._fields))
>> ...
> 
> 
> I didn't get the idea behind 'namedtuple' and your 'User._make(user[field]
> for field in User._fields)', I'm still using the other way:
> 
> import urllib.request
> import json
> 
> class User:
> 
> def __init__(self, steamid, personaname, lastlogoff, profileurl, avatar,
> timecreated, loccountrycode):
> self.steam_id = steamid
> self.persona_name = personaname
> self.last_logoff = lastlogoff
> self.profile_url = profileurl
> self.avatar = avatar
> self.time_created = timecreated
> self.country_code = loccountrycode
> 
> def fetch_users(*steamids):
> users = []
> 
> req = urllib.request.urlopen('
> 
http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=B9XXXXX20&steamids='
> + ','.join(steamids))
> user_list = json.loads(req.read().decode('utf-8'))["response"]["players"]
> 
> for user in user_list:
> if user["communityvisibilitystate"] == 3:
> users.append(User(user["steamid"], user["personaname"],
> user["lastlogoff"], user["profileurl"], user["avatar"],
> user["timecreated"], user["loccountrycode"]))
> 
> return users
> 
> As you guys said, I'd better use the "all open" pythonic way and not try
> to hide things, so here it's. Is this piece of code pythonic enough?

Yes, I think this is simple enough that you can easily understand it when 
you look at it again in a year. There are no constructs that strike me as 
unidiomatic.

It's time to stop pondering over the innards of this component and use it to 
build something useful. Good luck with that!


PS: This is not about being pythonic, but it might be more convenient for 
client code if you use datetime objects instead of timestamps:

>>> import datetime
>>> last_logoff = datetime.datetime.utcfromtimestamp(1410065399)
>>> print(last_logoff)
2014-09-07 04:49:59




More information about the Tutor mailing list