python class学习笔记

目录

1. 调用类方法的两种途径​​​​​​​

2. setters, getters

3.类属性

3. clean up hierarchy​​​​​​​

4. return a copy of the list

5. data hiding


OOP:

1. to bundle together objects that share some common properties(common attributes, procedures that operate on those attributes)

2. abstraction : 不需要知道实现的细节

1. 调用类方法的两种途径​​​​​​​

class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self, other):
        x_diff_sq = (self.x-other.x)**2
        y_diff_sq = (self.y-other.y)**2
        return (x_diff_sq + y_diff_sq)**0.5
  • 1)通过instance调用

        c = Coordinate(3, 4)

        origin = Coordinate(0, 0)

        print(c.distance(origin))

c -> object on which to call method

distance(origin) ->  method, parameters not including self, self is implied to be c

        2)直接通过类调用方法:

        c = Coordinate(3, 4)

        origin = Coordinate(0, 0)

        print(Coordinate,distance(c, origin))

Coordinate -> name of class

distance(c, origin) -> method,

parameters including an object on which to call the method, representing self

2. setters, getters

  • do not directly manipulate the internal representation of an object
  • to separate the use of the object from what's inside of it
  • anytime to access something inside an object, use the method that gets that part of the object out

 3.类属性

class Animal:
    id = 1  # 类属性

    def __init__(self):
        self.id = Animal.id
        Animal.id += 1  

    def get_id(self):
        print(self.id)


animal1 = Animal()
animal2 = Animal()

animal1.get_id()
animal2.get_id()

print(animal1.id)
print(animal2.id)

3. clean up hierarchy

before cleanup:

after cleanup:

4. return a copy of the list

5. data hiding

isolate the internal representation from the user:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值