我正在创建两个班级学生(基础)和详细信息。为什么不会学生将访问变量roll_No,class。?

时间:2015-05-02 05:43:44

标签: python inheritance

![在此输入图像描述] [1]我正在创建两个类student(base)和detail .Detail继承base的所有属性。我正在初始化base的属性(roll_no,name和class_stud)子类学生创建的子类的学生对象。子类()。这是代码:

student=type('student',(object,),{})       

def getinfo():  
    for studen in student.__subclasses__():
         studen.roll_no=input("enter the roll number")
         studen.name=input("enter the name of student")
         studen.class_stud=input("enter the class")


def printinfo():
     print('roll number ',roll_no,name,class_stud)

detail=type('detail',(student),{'info':getinfo(),'print':printinfo()})

ob=detail()
ob.info
ob.print

1 个答案:

答案 0 :(得分:1)

我从未见过有人以这种方式创建Python类,除非看看是否可以。你有很多错误,但这可能会做你想要的(虽然不是很清楚):

student=type('student',(object,),{})

def getinfo(self):
    for studen in student.__subclasses__():
         studen.roll_no=input("enter the roll number: ")
         studen.name=input("enter the name of student: ")
         studen.class_stud=input("enter the class: ")

def printinfo(self):
     print('roll number ',self.roll_no,self.name,self.class_stud)

detail=type('detail',(student,),{'info':getinfo,'print':printinfo})

ob=detail()
ob.info()
ob.print()

如您所见,您的主要错误是未将对象传递给方法。其他错误包括学生在定义细节时缺少逗号。另见@abarnert的评论。

这是一种用Python定义类的可怕方法。

编辑: 我不知道为什么要迭代子类,这可能是你对getinfo的意思:

def getinfo(self):
    self.roll_no=input("enter the roll number: ")
    self.name=input("enter the name of student: ")
    self.class_stud=input("enter the class: ")