[Tutor] Good approach regarding classes attributes

Juan Christian juan0christian at gmail.com
Mon Sep 8 19:26:52 CEST 2014


>
> > 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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140908/c2135a4f/attachment.html>


More information about the Tutor mailing list