[Tutor] advice on global variables

Alexandre Zani alexandre.zani at gmail.com
Tue Jul 10 23:32:10 CEST 2012


On Tue, Jul 10, 2012 at 1:32 PM, Prasad, Ramit
<ramit.prasad at jpmorgan.com> wrote:
>> You should avoid using the global statement.
>>
>> In your case, I would think you could just add an argument to the method:
>>
>> class MyObj(object):
>>     def __init__(self, arg):
>>         self.arg = arg
>>     def my_func(self, new_arg):
>>         self.arg = new_arg
>>
>> to call it:
>>
>> arg = 1
>>
>> m = MyObj(arg)
>> print m.arg
>> new_arg = 2
>> m.my_func(new_arg)
>> print m.arg
>
> Just as a note, this would not really work if the variable needs to be
> changed and read from several places when the value is an immutable
> type such as numbers / strings. In that case, then you could use
> the same logic but instead place the value in a list and pass that
> and always check/update the first element of the list.
>

That's a terrible idea. That's basically replicating the behavior of a
global while hiding that fact which makes the code even less readable.

>
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
> --
>
> This email is confidential and subject to important disclaimers and
> conditions including on offers for the purchase or sale of
> securities, accuracy and completeness of information, viruses,
> confidentiality, legal privilege, and legal entity disclaimers,
> available at http://www.jpmorgan.com/pages/disclosures/email.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list