[Tutor] How to Extend a class in another file in same directory

Dave Angel davea at ieee.org
Wed Apr 29 23:47:09 CEST 2009


sudhanshu gautam  wrote:

> <snip>
>
> 2.Now another file in which I want to extend that same parent class is here
> .First code running successfully but in another one having problem
>
>
> 'This another source code will represent the new Entry of database'
> import title
> class Newstudent(Studentdatabase):
>     def __init__(self,name,age,standard,place,dateofbirth,sex,marks):
>
> Studentdatabase.__init__(self,name,age,standard,place,dateofbirth,sex)
>         self.marks=marks
>         print 'The new data base has name of new students',self.name
>     def tell(self):
>         Studentdatabase.tell(self)
>         print 'The marks of the student is',self.marks
>
> s1=Newstudent('Rajiv',21,'M.B.A','MUMBAI','12 JAN,1987','MALE',267)
> s2=Newstudent('VIKASH',22,'M.B.A','DELHI','12 JAN 1985','MALE',234)
> s3=Newstudent('SAURAV',23,'B.TECH','BIHAR','12 JAN 1984','MALE',233)
> new=[s1,s2,s3]
> for newstudent in new:
>     newstudent.tell()
>
>
>
> Now tell me that how I can extend it
>   
You should tell the error message that you get, not just say "an 
error".  So we must guess.

If you want to refer to a name (Studentdatabase) in another module, you 
must import that module.  Assuming some things about your sys.path, that 
could be as simple as
    import title

This you did correctly.  Then referencing the name inside that other 
module is done by using

class Newstudent(title.Studentdatabase):



Note there is another choice, suitable if there's really only a single 
name you want to import:

from title import  Studentdatabase


That way, the name can be used without a prefix.  I usually prefer the 
first form, but the second has definite uses, especially if the import 
is of a module several levels down in a package hierarchy.



More information about the Tutor mailing list