此系列更新《Python Real World Data Science》的阅读摘记,每周六更新。
全书介绍Python在数据科学领域中的应用,分为四模块:
- Python 基础
- 数据分析
- 数据挖掘
- 机器学习
本文为系列第六篇,介绍python基础。
Chapter 6 When to use object-oriented programming
Treat objects as objects
- 识别出构建类的需求
Adding behavior to class data with properties
-
`class Color:
def init(self, rgb_value, name):
self.rgb_value = rgb_value
self._name = namedef _set_name(self, name):
if not name:
raise Exception("Invalid Name")
self._name = namedef _get_name(self):
return self._namename = property(_get_name, _set_name)`
-
使用属性包裹类成员,便于访问控制
Decorators – another way to create properties
-
`class Silly:
@property
def silly(self):
"This is a silly property"
print("You are getting silly")
return self._silly@silly.setter
def silly(self, value):
print("You are making silly {}".format(value))
self._silly = value@silly.deleter
def silly(self):
print("Whoah, you killed silly!")
del self._silly`
Deciding when to use properties
- method 名字通常为动词
- properties 设置或访问时可以自定义操作
- attributes 一般属性
Manager objects
- 可读性
- 拓展性
- 区分性
Don't Repeat Yourself (DRY)
- 少用ctrl + c
- always make the effort to refactor your code to be easier to read instead of writing bad code that is only easier to write.
网友评论