• 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()方法就可以了

     4-获取对象信息

      4.1使用type()函数

    type(123)#<class 'int'>
    type('str') #<class 'str'>
    type(123)==type(456) #True
    type('abc')==str #True
    type('abc')==type(123) #False
    
    import types 
    def fn():
        pass
    type(fn)==types.FunctionType#True
    type(abs)==types.BuiltinFunctionType #True
    type(lambda x: x)==types.LambdaType#True
    type((x for x in range(10)))==types.GeneratorType #True
    dir(types)  #可查看types常用常量

       4.2 isinstance使用

    #使用 isinstance, 对于class继承来说,type()就很不方便
    #如果继承关系是:object -> Animal -> Dog -> Husky
    isinstance(d, Dog) and isinstance(d, Animal) #true
    isinstance([1, 2, 3], (list, tuple)) #判断是某类型中的一种
    isinstance(b'a', bytes) #True

      4.3 dir使用

    #如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list
    dir('ABC')

     4.4 len(obj)

      我们自己写的类,如果也想用len(myObj)的话,就自己写一个__len__()方法

    4.5 getattr()、setattr()以及hasattr()

      仅仅把属性和方法列出来是不够的,配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态:

    class MyObject(object):
         def __init__(self):
             self.x = 9
         def power(self):
            return self.x * self.x
    obj = MyObject()
    hasattr(obj, 'x') # 有属性'x'吗? True
    setattr(obj, 'y', 19) # 设置一个属性'y'  
    getattr(obj, 'y') # 获取属性'y',如果不存在此属性会报异常
    getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404,

       实例属性和类属性

    class Student(object):
        name ='fengyong' #类的属性
        
    stu = Student()
    stu.name #fengyong
    stu.name = 'new Name'
    stu.name #new Name
    del(stu.name) #删除绑定的属性
    stu.name #fengyong 类属性的值

    从上面的例子可以看出,在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性

  • 相关阅读:
    老调重弹--面向对象设计原则--S.O.L.I.D设计原则
    老调重弹--面向对象设计原则--GRASP设计原则
    【C#版本详情回顾】C#4.0主要功能列表
    【C#版本详情回顾】C#3.0主要功能列表
    【C#版本详情回顾】C#2.0主要功能列表
    .NET Framework和C#版本历史概览
    springmvc RESTful
    springmvc之json交互
    springmvc上传图片
    springmvc异常处理
  • 原文地址:https://www.cnblogs.com/qinzb/p/9025537.html
Copyright © 2020-2023  润新知