[Baypiggies] What's the "Pythonic" way to access class attributes?

Sandip Bhattacharya sandipb at sandipb.net
Tue Oct 11 14:41:57 EDT 2016


I believe the Python way is not to use getFoo() or setFoo(), but obj.foo
directly.

You may however like to name the actual variable something else entirely
and expose foo using the property decorator  if you feel the need to manage
it within some sane parameters.

- Sandip

On Tue, Oct 11, 2016 at 10:51 AM, Craig Rodrigues <rodrigc at freebsd.org>
wrote:

> Hi,
>
> In various Python libraries and projects, I have seen that Foo.bar = 10
> is the preferred convention, since as you mentioned, there are no
> private/protected
> keywords in Python.
>
> You may want to look at the Python attrs library, which offers some
> interesting
> ways to use classes with attributions:
>
> https://glyph.twistedmatrix.com/2016/08/attrs.html
> https://attrs.readthedocs.io
>
> --
> Craig
>
>
> On Tue, Oct 11, 2016 at 2:29 AM, Braun Brelin <bbrelin at gmail.com> wrote:
>
>> Hello all,
>>
>> I just wanted to get the list's opinion on something.
>>
>> Since Python doesn't really have the concept of private and protected
>> attribute access protections a la Java or C++ (Yes, I know you can use
>> the __ and _ prefixes to declare something private or protected in
>> Python, but that really only does name-mangling on the attribute name
>> rather than explicitly disallow access to the attribute from outside the
>> class), is it better to still access the attribute directly a la
>> Foo.bar = 10 or use a setter/getter approach like Foo.setBar(10)?
>> It seems to me that option one is better, especially if I can use a
>> descriptor with the attribute.
>>
>> Any thoughts?
>>
>> Thanks,
>>
>> Braun Brelin
>>
>
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> https://mail.python.org/mailman/listinfo/baypiggies
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20161011/8b6cc218/attachment.html>


More information about the Baypiggies mailing list