Ben Ganzfried wrote:
Hey guys,
I'm using a tutorial geared for a 2.x version of Python and I am currently
using Python 3.1-- so it is possible that my confusion has to do with
different notations between them. But in any case, here is what I have:
My questions are the following:
1) Why is the type for my class Time : >>> type(Time)
<class 'type'>
when the type for their class Point is: <type 'classobj'>
In Python 2.x, objects are divided into two broad families of objects:
1. "classic classes" and their instances;
2. "new-style" types and their instances (including built-ins like str,
int, float, and similar).
There are some small, but significant differences between them, but in
general they do mostly the same kind of things.
In Python 2.x, a class definition like:
class Point:
...
defines a classic class (or "old style class"), while inheriting from
"object" or a built-in type defines a new-style class:
class Point(object): # Tells Python to construct a new-style class
...
The type of an instance is the instance's class; the type of a class
object is "classobj" for old-style classes and (usually) "type" for
new-style classes and types. Calling type() on old-style classes returns
<classobj>, and on new-style, <type>.
But in Python 3, old-style classic classes are gone. Point will be a
"type" object, which is what you are seeing.
Also, what is the difference between "class" and "classobj" in this case?
Every object has a type, even classes. `class` is the keyword that you
use for creating new classes, and type() is what you use to find out
what they are. So:
type(42) -> int # 42 is an int
type(int) -> type # int is a new-style class, or "type"
In Python 2.x, the type of a classic class is called "classobj", and the
type of a new-style class is called "type".
2) Why does my t1 object give the following as its type: <class
'__main__.Time'>
And in their p object example the type is: <type 'instance'>?
Again, this boils down to old-style vs. new-style.
3) What is happening such that when I try to call my print_time(t1) function
I get the following error:
t1 = Time()
t1.hours = 3
t1.minutes = 30
t1.seconds = 45
print_time(t1)
Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
print_time(t1)
NameError: name 'print_time' is not defined
You don't have a print_time function, as Python correctly reports. You
have a print_time *method*, which means it lives inside Time objects.
You can't access it directly as a global function:
print_time(something)
does not work, because print_time doesn't live in the global namespace.
You need to call it as a method of a Time instance:
t1.print_time() # no additional arguments needed
--
Steven
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor