Commit 88ba718d authored by caohaojun's avatar caohaojun

first commit

parent 3aff0803
# share-oop-py ## 重载和重写
* 重载(overload)
同一个类下,方法名相同,参数列表不同(参数列表类型不同 和 参数列表个数不同)
```python
def fn():
print(1)
def fn(a):
print(2)
def fn(a,b):
print(3)
```
python是没有重载的概念的,只能通过条件判断来实现类似重载
```python
def fn(a, b):
if isinstance(a, int):
print(1)
elif isinstance(a, float) and isinstance(b, int):
print(2)
else:
print(3)
```
* 重写(override
在类的继承关系中,子类和父类拥有相同的方法(参数列表相同),子类的实例对象调用该方法,那只会是子类的方法被调用,而父类的方法被重写
```python
class Animal:
def run(self):
print(123)
class Dog(Animal):
def run(self, dog):
print(456)
def run(self):
print(789)
```
## 变量和函数 | 属性和方法
* 变量和函数
基于面向过程的概念,定义的执行单位
```python
a=1
def fn():
print(123)
```
* 属性和方法
基于面向对象的概念,对象的特征就叫属性,对象的行为就叫方法。
本质上也是定义了变量和函数,但是因为附属于一个对象让属性和方法可以做的事情更具功能性
```python
class Aa:
a=1
def fn():
print(123)
aa=Aa()
print(aa.a)
aa.fn()
```
#### 属性
* 静态属性
属于类的属性,被定义在内存的静态区,比如Cat类有四条腿,直接通过类调用Cat.legsPython中通过类的实例化对象也可以调用)
```python
class Cat:
legs = 4
print(Cat.legs) # 类名直接调用
cat = Cat()
print(cat.legs) # 实例化对象调用
```
* 普通属性
严格意义上来说是属于实例化对象的属性,在类的函数中定义:self.xxx
```python
class Cat:
def __init__(self, name): # 构造函数
self.name = name
cat = Cat("小明")
print(cat.name)
# print(Cat.name)
```
#### 方法
* 静态方法
和静态属性的概念类似,使用@staticmethod修饰,使用时通过类直接调用,最常用的一个案例就是用来封装一个工具函数库
```python
class Cat:
@staticmethod
def run():
print(123)
Cat.run()
cat = Cat()
cat.run()
```
* 普通方法
类的实例化对象正常调用的方法
```python
class Cat:
def run(self):
print(123)
# Cat.run()
cat = Cat()
cat.run()
```
* 构造方法
就是在生成实例化对象的时候一定会执行的方法,python的构造方法是通过 \_\_new\_\_ 方法和 \_\_init\_\_ 方法来实现的, \_\_new\_\_ 方法主要来创建实例化对象,是一个静态方法, \_\_init\_\_ 方法主要来对实例化对象进行初始化。在创建对象的时候如果不需要执行一些初始化的操作,那么可以省略这两个函数,但其实在运行的时候,这两个函数还是会被执行
```python
class Cat:
def __new__(cls, *args, **kwargs):
pass
def __init__(self):
pass
class Cat2:
def __new__(cls, *args, **kwargs):
pass
def __init__(self, name):
# 初始化操作
self.name = name
```
* 其他内置方法( \_\_str\_\_ \_\_eq\_\_
所有的类都会继承一个终极的类objectobject会默认实现一些方法,比如 \_\_str\_\_ \_\_eq\_\_ \_\_str\_\_ 是用来在做一些输出操作(比如print)时,对输出对象做一些输出格式化操作的
```python
class Cat(object):
def __init__(self, name):
self.name = name
class Cat1(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "I am " + self.name
cat = Cat("小明")
cat1 = Cat1("小明")
print(cat)
print(cat1)
```
\_\_eq\_\_ 是用来在对象作 == 比较时调用的方法
```python
class Cat(object):
def __init__(self, name):
self.name = name
# def __eq__(self, other):
# return self.name == other.name
cat1 = Cat("小明")
cat2 = Cat("小明")
print(cat1 == cat2)
```
## 权限(public,protected,private)
Python 本身不存在这些权限的修饰词,而是通过变量名前增加下划线来区分
| 形式 | 具体权限 |
| :--------: | :----------------------------------------------------------: |
| xx | public公有变量,随处可以访问 |
| \_xx | protected型属性或方法,只有本类和子类可以访问,不可以import |
| \_\_xx | private属性或方法,只有本类可以访问,外部调用需要定义settergetter方法 |
| \_\_xx\_\_ | python内部定义的一些方法,不要自定义 |
| xx\_ | 一般用于避免和python的关键字冲突 |
此处主要举例私有属性
```python
# 模拟方式实现私有属性的调用
class Cat:
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
def setName(self, name):
self.__name = name
cat = Cat("小美")
print(cat.getName())
```
```python
# 使用@property装饰器实现私有属性的调用
class Cat:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
cat = Cat("小美")
print(cat.name)
```
## 继承(inheritance)
继承是面向对象最核心的内容,python是不严格的面向对象,所以在继承的时候,不会像Java这样的强类型面向对象语言,python的面向对象缺失了很多内容,或者说有些内容可以模拟实现,但是单独去讨论的意义不大,比如重载,比如多态。python本身是多继承。
在继承中,使用super可以调用父类的方法
```python
class A(object):
def run(self):
print("run A")
class B(A):
def run(self):
super().run()
print("run B")
b_ = B()
b_.run()
```
其中super()最常使用时就在 \_\_init\_\_ 方法中
```python
class A(object):
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
super(B, self).__init__()
self.x = self.x + 1
print(self.x)
b_ = B()
```
也可以直接调用父类的一个方法
```python
class A(object):
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
A.__init__(self)
self.x = self.x + 1
print(self.x)
b_ = B()
```
多继承情况
```python
class A(object):
def __init__(self):
print("A In")
class B(A):
def __init__(self):
print("B In")
super(B, self).__init__()
print("B Out")
class C(A):
def __init__(self):
print("C In")
super(C, self).__init__()
print("C Out")
class D(B, C):
def __init__(self):
print("D In")
super(D, self).__init__()
print("D Out")
d = D()
```
import RPi.GPIO as GPIO
import time
colors = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF]
R = 11
G = 12
B = 13
def setup(Rpin, Gpin, Bpin):
global pins
global p_R, p_G, p_B
pins = {'pin_R': Rpin, 'pin_G': Gpin, 'pin_B': Bpin}
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
for i in pins:
GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output
GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led
p_R = GPIO.PWM(pins['pin_R'], 2000) # set Frequece to 2KHz
p_G = GPIO.PWM(pins['pin_G'], 1999)
p_B = GPIO.PWM(pins['pin_B'], 5000)
p_R.start(100) # Initial duty Cycle = 0(leds off)
p_G.start(100)
p_B.start(100)
def map(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def off():
for i in pins:
GPIO.output(pins[i], GPIO.HIGH) # Turn off all leds
def setColor(col): # For example : col = 0x112233
R_val = (col & 0xff0000) >> 16
G_val = (col & 0x00ff00) >> 8
B_val = (col & 0x0000ff) >> 0
R_val = map(R_val, 0, 255, 0, 100)
G_val = map(G_val, 0, 255, 0, 100)
B_val = map(B_val, 0, 255, 0, 100)
p_R.ChangeDutyCycle(100 - R_val) # Change duty cycle
p_G.ChangeDutyCycle(100 - G_val)
p_B.ChangeDutyCycle(100 - B_val)
def loop():
while True:
for col in colors:
setColor(col)
time.sleep(1)
def destroy():
p_R.stop()
p_G.stop()
p_B.stop()
off()
GPIO.cleanup()
if __name__ == "__main__":
try:
setup(R, G, B)
loop()
except KeyboardInterrupt:
destroy()
# 在这里写上你的代码 :-)
import RPi.GPIO as GPIO
import time
DHTPIN = 11
GPIO.setmode(GPIO.BOARD)
MAX_UNCHANGE_COUNT = 100
STATE_INIT_PULL_DOWN = 1
STATE_INIT_PULL_UP = 2
STATE_DATA_FIRST_PULL_DOWN = 3
STATE_DATA_PULL_UP = 4
STATE_DATA_PULL_DOWN = 5
def read_dht11_dat():
GPIO.setup(DHTPIN, GPIO.OUT)
GPIO.output(DHTPIN, GPIO.HIGH)
time.sleep(0.05)
GPIO.output(DHTPIN, GPIO.LOW)
time.sleep(0.02)
GPIO.setup(DHTPIN, GPIO.IN, GPIO.PUD_UP)
unchanged_count = 0
last = -1
data = []
while True:
current = GPIO.input(DHTPIN)
data.append(current)
if last != current:
unchanged_count = 0
last = current
else:
unchanged_count += 1
if unchanged_count > MAX_UNCHANGE_COUNT:
break
state = STATE_INIT_PULL_DOWN
lengths = []
current_length = 0
for current in data:
current_length += 1
if state == STATE_INIT_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_INIT_PULL_UP
else:
continue
if state == STATE_INIT_PULL_UP:
if current == GPIO.HIGH:
state = STATE_DATA_FIRST_PULL_DOWN
else:
continue
if state == STATE_DATA_FIRST_PULL_DOWN:
if current == GPIO.LOW:
state = STATE_DATA_PULL_UP
else:
continue
if state == STATE_DATA_PULL_UP:
if current == GPIO.HIGH:
current_length = 0
state = STATE_DATA_PULL_DOWN
else:
continue
if state == STATE_DATA_PULL_DOWN:
if current == GPIO.LOW:
lengths.append(current_length)
state = STATE_DATA_PULL_UP
else:
continue
if len(lengths) != 40:
print("Data not good, skip")
return False
shortest_pull_up = min(lengths)
longest_pull_up = max(lengths)
halfway = (longest_pull_up + shortest_pull_up) / 2
bits = []
the_bytes = []
byte = 0
for length in lengths:
bit = 0
if length > halfway:
bit = 1
bits.append(bit)
print("bits: %s, length: %d" % (bits, len(bits)))
for i in range(0, len(bits)):
byte = byte << 1
if (bits[i]):
byte = byte | 1
else:
byte = byte | 0
if ((i + 1) % 8 == 0):
the_bytes.append(byte)
byte = 0
print(the_bytes)
checksum = (the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3]) & 0xFF
if the_bytes[4] != checksum:
print("Data not good, skip")
return False
return the_bytes[0], the_bytes[2]
def main():
print("Raspberry Pi wiringPi DHT11 Temperature test program\n")
while True:
result = read_dht11_dat()
if result:
humidity, temperature = result
print("humidity: %s %%, Temperature: %s C`" % (humidity, temperature))
time.sleep(1)
def destroy():
GPIO.cleanup()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
destroy()
def fn():
print(1)
def fn(a):
print(2)
def fn(a, b):
print(3)
fn(1,2)
\ No newline at end of file
def fn(a, b):
if isinstance(a, int):
print(1)
elif isinstance(a, float) and isinstance(b, int):
print(2)
else:
print(3)
fn(1, 2)
class Animal:
def run(self):
print(123)
class Dog(Animal):
def run(self, dog):
print(456)
def run(self):
print(789)
dog_01 = Dog()
# dog_01.run()
dog_01.run(1)
class Aa:
a = 1
def fn(self):
print(123)
aa = Aa()
print(aa.a)
aa.fn()
class Cat:
legs = 4
print(Cat.legs) # 类名直接调用
cat = Cat()
print(cat.legs) # 实例化对象调用
class Cat:
def __init__(self, name):
self.name = name
cat = Cat("小明")
print(cat.name)
# print(Cat.name)
class Cat:
@staticmethod
def run():
print(123)
Cat.run()
cat = Cat()
cat.run()
class Cat:
def run(self):
print(123)
# Cat.run()
cat = Cat()
cat.run()
class Cat:
def __new__(cls, *args, **kwargs):
pass
def __init__(self):
pass
class Cat2:
def __new__(cls, *args, **kwargs):
pass
def __init__(self, name):
# 初始化操作
self.name = name
class Cat(object):
def __init__(self, name):
self.name = name
class Cat1(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "I am " + self.name
cat = Cat("小明")
cat1 = Cat1("小明")
print(cat)
print(cat1)
class Cat(object):
def __init__(self, name):
self.name = name
# def __eq__(self, other):
# return self.name == other.name
cat1 = Cat("小明")
cat2 = Cat("小明")
print(cat1 == cat2)
class Cat:
def __init__(self, name):
self.__name = name
def getName(self):
return self.__name
def setName(self, name):
self.__name = name
cat = Cat("小美")
print(cat.getName())
class Cat:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
cat = Cat("小美")
print(cat.name)
class A(object):
def run(self):
print("run A")
class B(A):
def run(self):
super().run()
print("run B")
b_ = B()
b_.run()
class A(object):
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
super(B, self).__init__()
self.x = self.x + 1
print(self.x)
b_ = B()
class A(object):
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
A.__init__(self)
self.x = self.x + 1
print(self.x)
b_ = B()
class A(object):
def __init__(self):
print("A In")
class B(A):
def __init__(self):
print("B In")
super(B, self).__init__()
print("B Out")
class C(A):
def __init__(self):
print("C In")
super(C, self).__init__()
print("C Out")
class D(B, C):
def __init__(self):
print("D In")
super(D, self).__init__()
print("D Out")
d = D()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment