Python 练习3 定义类,类方法,实例方法
设计一个IP类:
设计1 要求:初始化时给定ip地址并判断ip地址的合法性
类方法:判断ip地址合法性
实例方法:将ip地址转化为10进制的表示形式及16进制的表示形式
例如:192.168.168.8 十进制形式为3232278536,十六进制形式为c0a8a808
设计2 要求:扩展要求1中ip类,使其实例化时增加子网掩码定义,并在初始化是判断子网掩码的合法性
实例方法:获取ip所属子网的网络号,广播地址,及子网内ip个数
设计1解析:
"""Ip address analyzer
Method:
dispIp: Display ip address.
intIp: Get integer of ip address.
hexIp: Get hex of ip address"""
from string import Template
class IpAddress(object):
'Ip address analyzer'
def __init__(self,ip):
'Initialize ip address and netmask'
assert IpAddress.isIp(ip),\
"ip is invalid"
self.ipAddr = ip
def isIp(cls,x):
'Determine if the ip address is valid'
aList = x.split(".")
if len(aList) != 4:
return False
else:
nList=[i for i in aList if (i.isdigit() and 0 <= int(i) <= 255)]
if len(nList) != 4: return False
else: return True
isIp=classmethod(isIp)
def __bin(self,x):
'Convert the decimal into binary,and return 8-bit binary. '
x = int(x)
if x == 0:
return '00000000'
else:
re = ''
while x > 0:
mod = x%2
x = x/2
re = str(mod) + re
differ = 8 - len(re)
re = ''.join(['0' for i in range(differ)]) + re
return re
def dispIp(self):
'Display ip address'
template = Template('IP: ${ipAddr}')
print template.substitute(ipAddr=self.ipAddr)
def intIp(self):
'Return integer of the ip address'
aList = self.ipAddr.split(".")
str2 = ''.join(self.__bin(i) for i in aList)
return str(int(str2, 2))
def hexIp(self):
'Return hex of the ip address'
aList = self.ipAddr.split(".")
retu
相关文档:
# -*- coding: utf-8 -*-
import urllib2
from BeautifulSoup import BeautifulSoup, Tag
import re
page = urllib2.urlopen("http://bj.ganji.com/piao/zz_%E5%8C%97%E4%BA%AC-%E5%8D%97%E6%98%8C/20100210/")
soup = BeautifulSoup(page)
#ss = soup.findAll('a', href=re.compile(r"^/piao/100.&qu ......
>>> import string
>>> s='adbecf'
>>>
tt=string.maketrans("abc","ABC")
>>> s.translate(tt,"")
'AdBeCf'
>>>
s.translate(tt,"")
后面的那个空字符创就是你要删除的字符,比如要删除换行就是s.translate(tt,"\n&q ......
原文
http://www.hetland.org/python/instant-hacking.php
Instant Hacking[译
文]
译者: 肯定来过 ......
url配置
我们在polls这个app下创建一个
helloworld.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, Django.")
修改 urls.py
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib ......
一些综合的信息
Python
里,缩进很重要。没有尖括号不要紧,
Python
根据缩进来分割语句块。
参数不需要定义,可以直接使用。
Help(var)
查看
var
的帮助。
Var
可以为任何东西,函数,模块,类。
Python
中的字符串是不可变的。
Pass
表示空语句块。
# 注释
String
r‘I&rsquo ......