Skip to content

Commit c32ec1e

Browse files
author
kangxiaoyu
committed
python的面向对象部分_类和实_访问限制_继承和多态_获取对象信_实例属性和类属性
1 parent eb4f5f4 commit c32ec1e

File tree

21 files changed

+319
-0
lines changed

21 files changed

+319
-0
lines changed

2017-04-26/module/hello.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/bin/env python
2+
# -*- coding:utf-8 -*-
3+
'a hello module'
4+
__author__='kxx'
5+
import sys
6+
def test():
7+
args=sys.argv
8+
if len(args)==1:
9+
print('Hello,world!')
10+
elif len(args)==2:
11+
print('Hello,%s!' % args[1])
12+
else:
13+
print('Too many arguments!')
14+
if __name__=='__main__':
15+
test()

2017-04-26/module/hello.pyc

523 Bytes
Binary file not shown.

2017-04-26/module/index.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<html>
2+
<head>
3+
<title>sanhai</title>
4+
</head>
5+
<body>
6+
<div>test</div>
7+
</body>
8+
</html>

2017-04-26/module/module.txt

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
,模块
2+
在计算机程序的开发过程中,随着程序代码越写越多。在一个文件里,代码就会越来越长,
3+
越来越不容易维护。
4+
为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里。这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。在Python中,一个。py文件就称之为一个模块(Module)
5+
使用模块有什么好处?
6+
最大的好处是大大提高了代码的可维护性。其次,编写代码不必从零开始。当一个模块编写完毕,就可以被其他地方
7+
引用。我们在编写程序的时候,也经常引用其他模块,包括Python内置的模块和来自第三方的模块。
8+
使用模块还可以避免函数名和变量名冲突。相同名字的寒舍变量完全可以分别存在不同的模块中,因此,我们自己在编写模块时,不必考虑名字会与其他模块冲突。但是也要注意,尽量不要与内置函数名字冲突。
9+
abs() dict() help() min() setattr()
10+
all() dir() hex() next() slice()
11+
any*( divmod() id() object() sorted()
12+
ascii() enumerate() input() oct() staticmethod()
13+
bin() eval() int() open() str()
14+
bool() exec() isinstance() ord() sum()
15+
bytearray() filter() issubclass() powd() super()
16+
bytes() float() iter() print() tuple()
17+
callable() format() len() property() type()
18+
char(). frozenset() list() range() vars()
19+
classmethod() getattrr() locals() repr() zip()
20+
compile() globals() map () reversed() __import__()
21+
complex hasattr max round
22+
deattr hash memoryview set()c78 个内置函数
23+
24+
你也许还想到,如果不同的人编写的模块名相同怎么办,为了避免模块冲突,Python
25+
又引入了按目录来组织模块的方法,称为包(Package).
26+
举个例子,一个abc.py的文件就是一个名字叫abc的模块,一个xyz.py的文件就是一个名字叫xyz的模块。
27+
28+
现在,假设我们的abc 和xyz这两个模块名字与其他模块冲突了。于是我们可以通过
29+
包来组织模块, 避免冲突。方法是选择一个顶层包名组织模块,避免冲突。方法选择一个顶层包名,
30+
31+
请注意,每一个包目录下面都会有一个__init__.py的文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包。__init__.py可以是空文件,也可以有Python代码,因为__init__.py本身就是一个模块,而它的模块名就是mycompany。
32+
33+
类似的,可以有多级目录,组成多级层次的包结构。比如如下的目录结构:
34+
35+
请不用使用python内置的模块命名
36+
自己创建模块时要注意命名,不能和Python自带的模块名称冲突。例如,系统自带了sys模块,自己的模块就不可命名为sys.py,否则将无法导入系统自带的sys模块。
37+
38+
mycompany.web也是一个模块,请指出该模块对应的.py文件。
39+
P地址,所以,IP地址对应的实际上是计算机的网络接口,通常是网卡。
40+
41+
42+
IP协议负责把数据从一台计算机通过网络发送到另一台计算机。数据被分割成一小块一小块,然后通过IP包发送出去。由于互联网链路复杂,两台计算机之间经常有多条线路,因此,路由器就负责决定如何把一个IP包转发出去。IP包的特点是按块发送,途径多个路由,但不保证能到达,也不保证顺序到达。
43+
44+
45+
P地址实际上是一个32位整数(称为IPv4),以字符串表示的IP地址如192.168.0.1实际上是把32位整数按8位分组后的数字表示,目的是便于阅读。
46+
47+
IPv6地址实际上是一个128位整数,它是目前使用的IPv4的升级版,以字符串表示类似于2001:0db8:85a3:0042:1000:8a2e:0370:7334。
48+
49+
TCP协议则是建立在IP协议之上的。TCP协议负责在两台计算机之间建立可靠连接,保证数据包按顺序到达。TCP协议会通过握手建立连接,然后,对每个IP包编号,确保对方按顺序收到,如果包丢掉了,就自动重发。
50+
51+
许多常用的更高级的协议都是建立在TCP协议基础上的,比如用于浏览器的HTTP协议、发送邮件的SMTP协议等。
52+
53+
一个IP包除了包含要传输的数据外,还包含源IP地址和目标IP地址,源端口和目标端口。
54+
55+
端口有什么作用?在两台计算机通信时,只发IP地址是不够的,因为同一台计算机上跑着多个网络程序。一个IP包来了之后,到底是交给浏览器还是QQ,就需要端口号来区分。每个网络程序都向操作系统申请唯一的端口号,这样,两个进程在两台计算机之间建立网络连接就需要各自的IP地址和各自的端口号。
56+
57+
一个进程也可能同时与多个计算机建立链接,因此它会申请很多端口。
58+
59+
了解了TCP/IP协议的基本概念,IP地址和端口的概念,我们就可以开始进行网络编程了。

2017-04-26/module/path.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/root/python1/python_execise/2017-04-26/module

2017-04-26/module/testb4.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/bin/env python
2+
from bs4 import BeautifulSoup
3+
soup = BeautifulSoup(open('index.html'),"html5lib")
4+
soup = BeautifulSoup("<html>data</html>","html5lib")

2017-04-26/module/using_module.txt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
使用模块
2+
Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用。
3+
我们以内建的sys模块为例
4+
5+
Python的内置的函数和模块。
6+
也要第三方的模块。模块就是由好多函数组成。
7+

2017-04-26/oop/Student.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/bin/env python
2+
# -*- coding:utf-8 -*-
3+
class Student(object):
4+
def __init__(self,name,score):
5+
self.name=name
6+
self.score=score
7+
def print_score(self):
8+
print('%s: %s' % (self.name,self.score))
9+
if __name__=='__main__':
10+
bart=Student('Bart Simpson',59)
11+
lisa=Student('Lisa Simpson',87)
12+
bart.print_score()
13+
lisa.print_score()

2017-04-26/oop/Student2.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#!/bin/env python
2+
clas Student(object):
3+
pass

2017-04-26/oop/Student3.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/bin/env python
2+
# -*- codinig:utf-8 -*-
3+
class Student(object):
4+
pass
5+
if __name__=='__main__':
6+
bart=Student()
7+
print bart
8+
print Student

2017-04-26/oop/Student_Bind.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/bin/env python
2+
# -*- codinig:utf-8 -*-
3+
class Student(object):
4+
pass
5+
if __name__=='__main__':
6+
bart=Student()
7+
bart.name='Bart Simpson'
8+
print bart.name
9+
#print bart
10+
#print Student
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/bin/env python
2+
# -*- coding:utf-8 -*-
3+
class Student(object):
4+
def __init__(self,name,score):
5+
self.name=name
6+
self.score=score
7+
if __name__=='__main__':
8+
bart=Student('Bart Simpson',59)
9+
print bart
10+
print bart.name
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/bin/env python
2+
# -*- coding:utf-8 -*-
3+
class Student(object):
4+
def __init__(self,name,score):
5+
self.__name=name
6+
self.__score=score
7+
def print_score(self):
8+
print('%s: %s' % (self.__name,self.__score))
9+
def get_name(self):
10+
return self.__name
11+
def get_score(self):
12+
return self.__score
13+
def set_score(self,score):
14+
if 0 <= score <= 100:
15+
self.__score=score
16+
else:
17+
raise ValueError('bad score')
18+
19+
if __name__=='__main__':
20+
bart=Student('Bart Simpson',98)
21+
print bart.__name
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/bin/env python
2+
# -*- coding:utf-8 -*-
3+
class Student(object):
4+
def __init__(self,name,score):
5+
self.name=name
6+
self.score=score
7+
def print_score(self):
8+
print('%s: %s' % (self.name, self.score))
9+
def get_grade(self):
10+
if self.score >=90:
11+
return 'A'
12+
elif self.score >= 60:
13+
return 'B'
14+
else:
15+
return 'C'
16+
if __name__=='__main__':
17+
bart=Student('张琰',120)
18+
a=bart.get_grade()
19+
print a
20+
21+

2017-04-26/oop/ensuplation/Student.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/bin/env python
2+
# -*- coding:utf-8 -*-
3+
class Student(object):
4+
def __init__(self,name,score):
5+
self.name=name
6+
self.score=score
7+
def print_score(self):
8+
print('%s:%s' % (self.name,self.score))
9+
if __name__=='__main__':
10+
bart=Student('zy','100')
11+
bart.print_score()

2017-04-26/oop/extend/Animal.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/bin/env python
2+
# -*- coding:utf-8 -*-
3+
class Animal(object):
4+
def run(self):
5+
print('Animal is running...')
6+
class Dog(Animal):
7+
def run(self):
8+
print('Dog is running...')
9+
def eat(self):
10+
print('Eating meat...')
11+
class Cat(Animal):
12+
def run(self):
13+
print('Cat is running...')
14+
if __name__=='__main__':
15+
dog=Dog()
16+
dog.run()
17+
cat=Cat()
18+
cat.run()
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
2+
pyright", "credits" or "license" for more information.
3+
>>> a='1'
4+
>>> type(a)
5+
<type 'str'>
6+
>>> a=1
7+
>>> type(a)
8+
<type 'int'>
9+
>>> a=[]
10+
>>> type(a)
11+
<type 'list'>
12+
>>> a={}
13+
>>> type(a)
14+
<type 'dict'>
15+
>>> a=[]
16+
>>> type(a)
17+
<type 'list'>
18+
>>> a=()
19+
>>> type(a)
20+
<type 'tuple'>
21+
>>> a=True
22+
>>> type(a)
23+
<type 'bool'>
24+
>>> a=1.2
25+
>>> type(a)
26+
<type 'float'>
27+
>>> a=u'1'
28+
>>> type(a)
29+
<type 'unicode'>
30+
>>> type(12)==type(456)
31+
True
32+
>>> type(123)=int
33+
File "<stdin>", line 1
34+
SyntaxError: can't assign to function call
35+
>>> type(123)==int
36+
True
37+
>>> type('123')==type('123')
38+
True
39+
>>> type('abc')==str
40+
True
41+
>>> type('abc')==type(123)
42+
False
43+
>>> import types
44+
>>> def fn():
45+
... pass
46+
...
47+
>>> type(fn)==types.FunctionType
48+
True
49+
>>> type(abs)==types.BuiltinFunctionType
50+
True
51+
>>> type(lambda x:x)==types.LambdaType
52+
True
53+
>>> type((x for x in range(10)))==types.GeneratorType
54+
True
55+
>>>

2017-04-26/oop/using_dir/getattr.txt

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
紧接着,可以测试该对象的属性:
2+
3+
>>> hasattr(obj, 'x') # 有属性'x'吗?
4+
True
5+
>>> obj.x
6+
9
7+
>>> hasattr(obj, 'y') # 有属性'y'吗?
8+
False
9+
>>> setattr(obj, 'y', 19) # 设置一个属性'y'
10+
>>> hasattr(obj, 'y') # 有属性'y'吗?
11+
True
12+
>>> getattr(obj, 'y') # 获取属性'y'
13+
19
14+
>>> obj.y # 获取属性'y'
15+
19
16+
如果试图获取不存在的属性,会抛出AttributeError的错误:
17+
18+
>>> getattr(obj, 'z') # 获取属性'z'
19+
Traceback (most recent call last):
20+
File "<stdin>", line 1, in <module>
21+
AttributeError: 'MyObject' object has no attribute 'z'
22+
可以传入一个default参数,如果属性不存在,就返回默认值:
23+
24+
>>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404
25+
404
26+
也可以获得对象的方法:
27+
28+
>>> hasattr(obj, 'power') # 有属性'power'吗?
29+
True
30+
>>> getattr(obj, 'power') # 获取属性'power'
31+
<bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
32+
>>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn
33+
>>> fn # fn指向obj.power
34+
<bound method MyObject.power of <__main__.MyObject object at 0x10077a6a0>>
35+
>>> fn() # 调用fn()与调用obj.power()是一样的
36+
81
37+
小结
38+
39+
通过内置的一系列函数,我们可以对任意一个Python对象进行剖析,拿到其内部的数据。要注意的是,只有在不知道对象信息的时候,我们才会去获取对象信息。如果可以直接写:
40+
41+
sum = obj.x + obj.y
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
>> dir('12')
2+
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
3+
>>>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
使用dir()
2+
相对了man
3+
如果相获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list.
4+
比如,获得一个str对象的所有属性后方法。
5+
6+
类似__xxx__的属性和方法在Python中都是有特殊用途的,比如__len__方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的__len__()方法,所以,下面的代码是等价的:

2017-04-26/oop/获取对象信息.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
获取对象信息
2+
当我们拿到一个对象的引用时,如何知道这个对象是什么类型,有哪些方法呢?
3+
使用type()
4+
首先,我们来判断对象类型,使用type()函数:
5+
基本类型都可以用type()判断

0 commit comments

Comments
 (0)