面向对象的编程-类和实例

定义类是通过class关键字:

class Student(object):
    pass

来实现的 

  面向对象作为python的优势之一,相关概念的理解难度和重要程度仅次于封包(是否理解封包的原理可以看作python是否真正入门的一道坎) 

  上代码:

#-*- coding:utf-8 -*-

#main1
class Student(object):

    def __init__(self,name,score):
        self.name=name
        self.score=score

    def print_score(self):
        print('%s:%s' %(self.name,self.score))

    def get_grade(self):
        if self.score>=90:
            return 'A'
        if self.score>=60:
            return 'B'
        else:
            return 'C'
        
#test1
bart=Student('Bart Simpson',59)
print(bart.name)
print(bart.score)
bart.print_score()
#test2
lisa=Student('Lisa',99)
bart=Student('Bart',59)
print(lisa.name,lisa.get_grade())
print(bart.name,bart.get_grade())

  通过Student类,实现了将多个功能的封闭,在调用时仅需要调用该类中的函数,而不必清楚其原理

  

猜你喜欢

转载自www.cnblogs.com/victorslave/p/10361202.html