creating instances of classes?

Tony J Ibbs (Tibs) tony at lsl.co.uk
Thu Mar 9 05:07:50 EST 2000


Shaun Hogan wrote:
> i want the code below to tell me the current time & date when i
> execute it,
>
> class telltime:
>     def __init__(self,time,date):                         <1>
>         import time
>         self.time==time.localtime(time.time())[3:6]       <2>
>         self.date==time.localtime(time.time())[0:3]
>         self.time=time                                    <3>
>         self.date=date
>     def op(self):
>         print self.time
>         print self.date
> t=telltime(time,date)                                     <4>
> print t.op()                                              <5>

Well, it's *almost* there. Here are some comments...

<1> If you're wanting the class to *calculate* the time and date, there's no
need to pass them down... (see <4> below as well)

<2> You've used "==" here, which does a comparison - "=" is the assignment
operator

<3> This overwrites the values you just calculated...

<4> "time" and "date" aren't declared at this level, so it will grumble
about them (what value are they meant to have here, anyway?). They can be
removed...

<5> See below...

So the script should probably be:

class telltime:
    def __init__(self):
        import time
        self.time=time.localtime(time.time())[3:6]
        self.date=time.localtime(time.time())[0:3]
    def op(self):
        print self.time
        print self.date
t=telltime()
print t.op()

which, when executed, prints out:

	(10, 0, 59)
	(2000, 3, 9)
	None

That final None is because "op" is returning None (because you didn't tell
it to do anything else), and the final "print" is printing what "t.op"
returns (the time/date values were printed by t.op already).

So the last line *really* just needs to be:

t.op()

Does this make some sense?

Tibs

--
Tony J Ibbs (Tibs)      http://www.tibsnjoan.demon.co.uk/
Feet first with 5 wheels...
My views! Mine! Mine! (Unless Laser-Scan ask nicely to borrow them.)






More information about the Python-list mailing list