[Tutor] Object/Class Beginner Questions
Alex Hall
mehgcap at gmail.com
Fri Jan 14 22:28:16 CET 2011
On 1/14/11, Ben Ganzfried <ben.ganzfried at gmail.com> 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:
>
>>>> type(Time)
> <class 'type'>
>>>> t1 = Time()
>>>> type(t1)
> <class '__main__.Time'>
>
> where:
>
> class Time:
> def __init__(self, hours = 0, minutes = 0, seconds = 0):
> self.hours = hours
> self.minutes = minutes
> self.seconds = seconds
>
> def print_time(t1):
> print(t.hours, ":", t.minutes, ":", t.seconds)
>
> Now the book I am working with has the following example:
>
>>>> type(Point)
> <type 'classobj'>
>>>> p = Point()
>>>> type(p)
> <type 'instance'>
>
> 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'>
> Also, what is the difference between "class" and "classobj" in this case?
I am not sure as I thought something changed about this in 3.x, but try:
class time(object)
instead of simply
class time
and see what happens.
> 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'>?
I am not sure, and am curious to see the answer as well.
> 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 made a time object. This means that everything about the object
(class) is accessed through the dot notation. Currently, you are
calling print_time(t1) where t1 is an object. You have to, as they
say, call print_time on an instance of the time class. You have an
instance, t1 (an instance is just a variable representing the class),
so call print_time on the instance:
t1.print_time()
HTH.
>
>
> Thank you very much.
>
> Sincerely,
>
> Ben
>
--
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap
More information about the Tutor
mailing list