日常python学习-6

2018.3.13

1.python的OOP

直接看例子:

class Student(object):
    pass

类名一般大写,括号内部表示继承.如果没有合适的继承类,就直接继承object类.

这里OOP最大的不同是一个实例可以绑定各种数据,同一个类的两个实例的变量名可以有很大区别:

bob = Student()
bob.name = 'bob'

这种为实例随意增加变量的属性是动态语言特有的.

更加规范的,加上方法的类的写法如下:

class Student(object):

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

    def get_grade(self):
        if self.grade > 95:
            print('4.3')
        elif self.grade >90:
            print('4.0')
        else:
            print('less than 4.0')

    def print_score(self):
        print("%s : %s" % (self.name,self.grade))

构造函数的写法就是利用一个特殊的__init__方法,第一个参数必须是self. 其余的方法写法和python写函数的区别也就在一个self变量.没什么太大区别.调用方法的时候self是解释器自动传进去的,不用多管:

bob = Student('bob',95)
bob.get_grade()
bob.print_score()
2.私有属性

python的私有属性定义的时候以双下划线开头,这样就让外部无法直接访问.设置私有属性更改值之类的都用方法来实现,这样可以检查参数,保证没有无效值出现.

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 set_score(self,score):
        self.__score = score
3.多态性质

由于有继承,那么子类就可以直接调用父类方法.如果需要覆盖,直接覆盖即可很方便

4. type()函数

拿到一个对象,要知道它是什么类的实例,可以使用type方法,type的返回值就是该对象的类:

>>> type(123)==type(456)
True
>>> type(123)==int
True
>>> type('abc')==type('123')
True
>>> type('abc')==str
True
>>> type('abc')==type(123)
False
5.isinstance()
>>> a = Animal()
>>> d = Dog()
>>> h = Husky()
>>>> isinstance(h, Husky)
True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值