python-6面向对象编程

1-类和实例

class Student(object):
    def __init__(self, name, score):# _init__方法的第一个参数永远是self,表示创建的实例本身
        self.name = name
        self.score = score
    def print_score(self):
        print('nams:%s, score:%s'%(self.name,self.score))
    def get_grade(self):
        if(self.score >=90):
            return 'A'
        elif(self.score >= 60):
            return 'B'
        else:
            return 'C'

#调用   
stu = Student('qinzhongbao',79)
stu.print_score()
print(stu.get_grade())

2-访问限制
  例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问

class Person(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score =score
    def print_score(self):
        print('name:%s,score:%s'%(self.__name,self.__score))
    def get_name(self):
        return self.__name
    
person = Person('fengyong',88)
person.__name ='newName' #修改值
print(person.__name) #newName
print(person.get_name()) #fengyong 修改值没有生效

3-继承和多态

class Animal(object): #继承object
    def run(self):
        print('Animal is running')
        
class Dog(Animal): #继承Animal
    def run(self):
        print('Dog is running')
        
class Cat(Animal):
    def run(self):
        print('Cat is running')

        
def run(animail):
     animail.run()
     
animal = Animal()
run(animal)    
run(Dog())
run(Cat())
#对于Python这样的动态语言来说,则不一定需要传入Animal类型。
#我们只需要保证传入的对象有一个run()方法就可以了

猜你喜欢

转载自www.cnblogs.com/qinzb/p/9025537.html