W7_staticmethod_classmethod_property_反射_exception_socket

Posted rootid

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了W7_staticmethod_classmethod_property_反射_exception_socket相关的知识,希望对你有一定的参考价值。

[TOC]
#94.第03章节-Python3.5-静态方法、类方法、属性方法
静态方法:只是看似归类管理,实际上在静态方法里访问不了类或实例中的任何属性
类方法:只能访问类变量,不能访问实例变量
属性方法:把一个方法变成一个静态属性


#97.第06章节-Python3.5-深入讲解类的特殊成员方法__new__等
类的另一种构造:
def func(self):
print("hello %s" % self.name)

def __init__(self,name,age):
self.name = name
self.age = age

Foo = type("Foo",(object,), {"talk":func , "__init__":__init__})
f = Foo("Chrn",22)
f.talk()

#98.第07章节-Python3.5-反射详解1
hasattr(obj.name_str) #判断一个对像obj里是否有对应的name_str字符串的方法
getattr(obj.name_str) #根据字符串去获取obj对象里的对应的方法的内存地址

class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("%s is eating %s" % (self.name, food))
d = Dog("no1_dog")
choice = input(">>:").strip()
if hasattr(d,choice):
func = getattr(d,choice)
func("baozi")
setattr(obj,"string",v) # is equivalent to ‘‘obj.string = v‘‘
delattr(obj,y) # is equivalent to ‘‘del obj.y‘‘

 

#100.第09章节-Python3.5-异常处理TryExcept
##异常语法

```
data = {}
list = [1,2]

try:
data["name"]
list[3]
open("fdsafdf")
a = 1
except KeyError as e:
print("字典没有这个key", e)
except IndexError as e:
print("列表没有这个索引",e)
except (KeyError,IndexError) as e: #把多项合并的写法,多项异常执行同一操作
print("出错了:", e)
except Exception as e:
print("未知错误",e)
else:
print("一切正常")
finally:
print("不管正常与否,都得执行")


#python2.7的写法:中间使用逗号隔开
#except KeyError, e:
```
##自定义异常

```
class Wuexcetion(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return self.msg

# db_conn_e = Wuexcetion("test db connection exception")
# print(db_conn_e)

conn_status = 2
# conn_status = 1

try:
if conn_status > 1:
raise Wuexcetion("数据库没有连接上")
else:
pass
except Wuexcetion as e:
print(e)
```

#101.第10章节-Python3.5-网络编程Socket介绍1


#102.第11章节-Python3.5-网络编程Socket介绍2

##socket_client

```
import socket
client = socket.socket()
client.connect((‘localhost‘,6969))
client.send(b"hello world")
data = client.recv(1024)
print("recv:",data)
client.close()
```

##socket_server

```
import socket
server = socket.socket()
server.bind((‘localhost‘,6969))
server.listen()
print("我要开始等电话了")
conn,add = server.accept()
print("电话打进来了")
data = conn.recv(1024)
conn.send(data.upper())
print("recv:",data)
server.close()

```



















































































以上是关于W7_staticmethod_classmethod_property_反射_exception_socket的主要内容,如果未能解决你的问题,请参考以下文章