[Tutor] Good approach regarding classes attributes
Peter Otten
__peter__ at web.de
Sun Sep 7 10:04:25 CEST 2014
Juan Christian wrote:
> I'm writing a program that have a 'User' class. This class will have the
> following attributes:
>
> 1. id
> 2. personaname
> 3. lastlogoff
> 4. profileurl
> 5. avatar
> 6. realname
> 7. timecreated
> 8. loccountrycode
>
> I'm thinking about writing something like that:
> class User():
>
> def __init__(id):
> self.__id = id
>
> [URL Request to call API and get everything using the ID (JSON)]
>
> self.__personaname = [JSON response personaname]
> [...]
>
> def get_id():
> return __id
>
> def get_personaname():
> return __personaname
>
> [...]
> Is it a good approach, is this phytonic?
It's not a good approach and it's not pythonic.
In Python you should avoid accessor functions and (pseudo-)private
__attributes ("Python is not Java"). So
class User:
def __init__(self, id):
self.id = id
# load attributes
self.personname = [personname from JSON]
...
user = User(42)
is certainly better. You might also consider making the class less dependent
of the way you acquire the corresponding data:
class User: # in Python 2: class User(object): ...
def __init__(self, id, personname, ...)
self.id = id
self.personname = personname
...
@classmethod
def from_id(class_, id):
# load attributes
return User(id, personname, ...)
jeff = User(42, "Jeff", ...)
jack = User.from_id(43)
More information about the Tutor
mailing list