首页 > 代码库 > python:创建类的实例

python:创建类的实例

 

class Student(object):
  def __init__(self,name="",school="",grade=""):
    if not name:
        name=raw_input("What is the student‘s name?")
    if not school:
        school=raw_input("What is the student‘s school?")
    if not grade:
        grade=self.get_grade()
    self.name=name
    self.school=school
    self.grade=grade
    self.print_student()
  def get_grade(self):
    while True:
      grade=raw_input("What is the student‘s grade?[k,1-5]")
      if grade.lower() not in [‘k‘,‘1‘,‘2‘,‘3‘,‘4‘,‘5‘]:
        print "I‘m sorry ,but {} isn‘t valid.".format(grade)
      else:
        return grade
  def print_student(self):
    print "Name: {}".format(self.name)
    print "School: {}".format(self.school)
    print "Grade: {}".format(self.grade)

 

def main():
  student1=Student()
  student2=Student(name="harry",grade="2",school="Minnieville")


if __name__=="__main__":
  main()


注意:1.创建的类中必须有参数Object
2."!"变成中文符号‘hello world\xa3\xa1‘可能出现错误
3.类中的方法传入值必须有self,在方法体中用self引用属性
4.调用该类时,不用复写object
5.__name__、__main__和__init__均是双下划线
6.python自带的初始化方法__init__(),在调用该类时自动调用该方法

python:创建类的实例