Newbie class questions
toby at puckish.demon.co.uk
Thu Jun 10 18:59:30 EDT 1999
I have just started to learn Python (v1.5.2), and have some questions
about classes. Here is something I prepared earlier...
--- cut ---
def y(x): return 'a global function y(x)'
def g0(): return 'some arbitrary function (no args)'
def g1(x): return 'another arbitrary function (one arg)'
i = 0
"""A simple class demonstrating scope."""
i = 12345
print '\n\tI output, therefore I am.\n'
return 'default class method y'
# i = 7 # hides global
print 'Global variable:', i
print 'Class variable:', MyClass.i
print 'Instance variable:', x.i
print 'Global function:', y(x)
print 'Class method:', MyClass.y(x) # explicit instance arg.
print 'Instance method:', x.y() # implicit instance arg.
"""This method is inaccessible - should be a parse-time error"""
t = MyClass()
print "Doc:", t.__doc__
i = 21
t.i = 169
#t.y = g1
t.y = g0
--- cut ---
BTW I think an example class like this in the tutorial would help
explain scope, but there are also a few things I don't understand here
(probably my C++ background).
(1) Is there a reason why I cannot call MyClass.q()? Why require a
meaningless instance arg to a class-static method? Alternatively
shouldn't it be an error at parse time?
(2) Why doesn't t.y = g1 work? How am I meant to access instance
attributes in g0 without an instance argument?
(3) Some mention was made in the tutorial of the scope rules being in
flux. Are any impending changes likely to affect the output of this
More information about the Python-list