Quirk difference between classes and functions

DL Neil PythonList at DancesWithMice.info
Mon Feb 25 14:56:25 EST 2019


On 26/02/19 5:25 AM, ast wrote:
> I noticed a quirk difference between classes and functions
>  >>> x=0
>  >>> class Test:
>          x = x+1
>          print(x)
>          x = x+1
>          print(x)
...

> Previous code doesn't generate any errors.
> x at the right of = in first "x = x+1" line is
> the global one (x=0), then x becomes local
> within a function, this is not allowed
>  >>> x = 0
>  >>> def f():
>          x = x+1
>  >>> f()
> UnboundLocalError: local variable 'x' referenced before assignment
> Since x is written inside the function, it is considered as a local
> variable and x in x+1 is undefined so this throw an exception
> Any comment ?


At first I misunderstood the question, and even now I'm slightly mystified:-

Is the observation to do with the principles of "closure" (being applied 
to the function) compared with the differences between class and 
instance variables?

For a little more fun, try expanding Test with:
	def __init__( self ):
		self.x = "something else"

What happens when you look at Test.__dict__?

What happens after instantiation:

t = Test()
print( t.__dict__ )

For extra credit: how does this change if we try modifying attributes 
from 'outside' the class definition?

t.x = 3.333333

Are they all 'the same' or 'all different'?


A question from me: (I'm not an O-O 'native' having taken to it long 
after first learning 'programming') I've used class attributes to hold 
'constants', eg

	MAXIMUM_WEIGHT = 100

Thus only an assignment to which reference/assertions will be made 'later'.

I have initialised a counter to zero and then incremented within the 
instantiated object's __init__(), ie keeping track of how many of 'these 
objects' have been instantiated.

So, I can imagine taking a value from outside the class' namespace, 
modifying it in some way (per the first "x = x+1") and then retaining 
the result as a class attribute (a calculation performed once - when the 
class code is compiled).

However, (after that first calculation/definition of the class 
attribute) why would one (normally) want to redefine the same class 
attribute (the second x = x+1), at the 'class level'?
(perhaps just done for its amusement value?)

-- 
Regards =dn



More information about the Python-list mailing list