Newbie class questions

Toby Kelsey toby at puckish.demon.co.uk
Fri Jun 11 00:59:30 CEST 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
class MyClass:
  """A simple class demonstrating scope."""
  i = 12345
  def __init__(self):
    print '\n\tI output, therefore I am.\n'
  def y(x):
    return 'default class method y'
  def f(x):
    # 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.
    return
  def q():
    """This method is inaccessible - should be a parse-time error"""
    return

t = MyClass()
print "Doc:", t.__doc__
t.f()
print "\nModified:"
i = 21
t.i = 169
#t.y = g1
t.y = g0
t.f()
--- 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
class?

Cheers,
Toby
-- 
Toby Kelsey




More information about the Python-list mailing list