my code goes like this
global php
php = 1
class add_s_f_g_v_php:
def r(php):
phpt = php
php = phpt+phpt
return php
add_s_f_g_v_php.r(php)
print(php)
and it gives me 1 like it didn't change
I tryed adding return and making the var global.
You should put global
inside function:
php = 1
class add_s_f_g_v_php:
def r(php):
global php
phpt = php
php = phpt+phpt
add_s_f_g_v_php.r(php)
print(php)
OR Re-assign back
php = 1
class add_s_f_g_v_php:
def r(php):
phpt = php
php = phpt+phpt
return php
php = add_s_f_g_v_php.r(php)
print(php)
I usually avoid this kind of problem. Most of the time if you need to do this, there is probably a design flaw somewhere. Anyhow, I see two ways of doing it without reassignment. Both use, as in the other answers, the global
keyword (Note: I do not see how---in the present form---the other answers actually would work).
php = 1
print( php )
class changer( object ): ## object not required in Python3 but I am used to put it
#method 1
def php_adder_1( self, adder ):
global php
php += adder
#method 2
@classmethod
def php_adder_2( cls, adder ):
global php
php += adder
### is applied in the following ways:
myobj = changer()
myobj.php_adder_1( 3 )
print( php )
changer().php_adder_2( 30 )
print( php )
### and this would also work
myobj.php_adder_2( 300 )
print( php )
providing
>> 1
>> 4
>> 34
>> 334
Check out, eg, this on @classmethod
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.