Re: Chapter 9 Tutorial for Classes Not Working



class MyClass:
"A simple example class"
i = 12345
def f(self):
return 'hello world'

Nothing wrong with this.

From here I run:
x = MyClass

Here's your problem - x is a class, *not* an instance of a class (i.e.
an object). Methods
operate on objects, not classes. Try x = MyClass() instead to get an
instance of the class.

xf = x.f
while True:
print xf()

Why not try something simpler - it doesn't look like you really know
what you are doing here. The while True is going to print your "hello
world" until the end of time, and there is no value in assigning the
function to a variable at this stage - its adding complexity which you
don't seem to need at the moment...

Try:

x = MyClass()
x.f()

.



Relevant Pages

  • Re: adding methods at runtime
    ... myattr = "myattr" ... def method: ... instance.method = new.instancemethod(method, instance, myclass) ... The lookup mechanism will then invoke the descriptor protocol on the function object, which will return a method. ...
    (comp.lang.python)
  • Re: Dynamically generating classes?
    ... >> def initialize ... > def create_class(name, parent = nil) ... > klass = Class.new ... "MyClass" ...
    (comp.lang.ruby)
  • Re: overloading *something
    ... >>> How does one make an arbitrary class ) behave ... >>> I've looked at getitem, getslice, and iter. ... >> def totuple: ... >> myargs = myclass() ...
    (comp.lang.python)
  • Re: Class Methods help
    ... we have "instance method". ... class MyClass: ... def some_func: ...
    (comp.lang.python)
  • Re: return same type of object
    ... This is usually known as a 'factory method'. ... return MyClass() ... def create: ... return PsychoRigid() ...
    (comp.lang.python)