本节内容:

  • 面向对象高级语法部分异常处理异常处理异常处理

    • 经典类vs新式类  
    • 静态方法、类方法、属性方法
    • 类的特殊方法
    • 反射
  • 异常处理
  • 作业:开发一个支持多用户在线的FTP程序

面向对象高级语法部分

1、经典类vs新式类

参考:http://www.cnblogs.com/ant-colonies/p/6719724.html

2、实例方法、静态方法、类方法、属性方法

2.1 实例方法

 # -*- coding:utf-8 -*-
# class Dog(object):
def __init__(self, name):
self.name = name
print('name = %s' %self.name)
def sleep(self):
print('going to sleep...') print(Dog.sleep)
'''<unbound method Dog.sleep>''' Dog.sleep()
'''
Traceback (most recent call last):
File "py_instance.py", line 12, in <module>
Dog.sleep()
TypeError: unbound method sleep() must be called with Dog instance as first argument (got nothing instead)
'''
'''
Dog.sleep是未绑定的方法
必须以类Dog的实例对象作为未绑定的方法sleep()的第一参数,sleep方法才能被调用
'''

未实例化类调用实例方法

 # -*- coding:utf-8 -*-
# class Dog(object):
def __init__(self, name):
self.name = name
print('self.name = %s' %self.name)
print('self : %s' %type(self))
def sleep():
print('going to sleep...') d = Dog('Tim')
print(d.sleep)
d.sleep() '''
一旦实例化, __init__方法立即执行
self.name = Tim self是一个类对象
self : <class '__main__.Dog'> 通过实例化,使得Dog.sleep实现绑定
<bound method Dog.sleep of <__main__.Dog object at 0x7ffa7deeedd0>> d.sleep()将实例对象作为第一参数传给sleep方法,但是sleep方法无形参
Traceback (most recent call last):
File "py_instance.py", line 14, in <module>
d.sleep()
TypeError: sleep() takes no arguments (1 given)
'''

实例方法无形参

 # -*- coding:utf-8 -*-
# class Dog(object):
def __init__(self, name):
self.name = name
print('self.name = %s' %self.name)
print('self : %s' %type(self))
def sleep(name):
print('%s going to sleep...' %name)
print('%s going to sleep...' %name.name) d = Dog('Tim')
print(d.sleep)
d.sleep() '''
self.name = Tim
self : <class '__main__.Dog'> 实例对象的内存地址
<bound method Dog.sleep of <__main__.Dog object at 0x7fb3f2605dd0>> 诶,实例对象传给了name
<__main__.Dog object at 0x7f98f2176ed0> going to sleep...
Tim going to sleep...
'''

实例方法中第一参数为实例对象

 # -*- coding:utf-8 -*-
# class Dog(object):
def __init__(self, name):
self.name = name
print('self.name = %s' %self.name)
print('self : %s' %type(self))
def sleep(self):
print('%s going to sleep...' %self.name) d = Dog('Tim')
print(d.sleep)
d.sleep() '''
self.name = Tim
self : <class '__main__.Dog'>
<bound method Dog.sleep of <__main__.Dog object at 0x7f627e678e90>> python中实例方法中的第一参数为实例对象本身, 默认self作为第一形参
Tim going to sleep...
'''

Python中实例方法中形参的默认表示方式

 # -*- coding:utf-8 -*-
# class Dog(object):
def __init__(self, name):
self.name = name
print('self.name = %s' %self.name)
print('self : %s' %type(self))
def sleep(self):
print('%s going to sleep...' %self.name) d = Dog('Tim')
f = Dog('Tim')
print(d == f)
print(d.sleep is f.sleep()) '''
self.name = Tim
self : <class '__main__.Dog'>
self.name = Tim
self : <class '__main__.Dog'> 实例化出两个对象
False
Tim going to sleep...
False
'''

实例化多个对象

2.2 静态方法

 # -*- coding:utf-8 -*-
# class Dog(object): stat = 'awake' def __init__(self):
pass
#print('self.name = %s' %self.name)
#print('self : %s' %type(self)) @staticmethod
def sleep():
print('going to sleep...') print(Dog.stat)
print(Dog().stat)
print(type(Dog.stat))
print(type(Dog().stat))
Dog.sleep()
Dog().sleep()
print(Dog.sleep)
print(Dog().sleep)
print(Dog.sleep is Dog.sleep)
print(Dog().sleep is Dog.sleep) '''
静态方法与类变量性质相似,逻辑上隶属于类,其实独立于类,不受类的影响
awake
awake
<type 'str'>
<type 'str'>
going to sleep...
going to sleep...
<function sleep at 0x7f3f3fb238c0>
<function sleep at 0x7f3f3fb238c0>
True
True
'''

静态方法与类变量的比较

 # -*- coding:utf-8 -*-
# class Dog(object): def __init__(self, name):
self.name = name
print('self.name = %s' %self.name) @staticmethod
def sleep(self):
static_var = 'STATIC'
print('%s is going to sleep...%s' %(self, static_var)) Dog('Tim').sleep('Jerry')
print(Dog.sleep('Jerff').static_var)
Dog.sleep('Jerff').static_var = 'Here'
print(Dog.sleep('Jerff').static_var) """
静态方法相当于类变量,是一块代码块逻辑,不存在静态方法内部的调用问题
self.name = Tim
Jerry is going to sleep...STATIC
Jerff is going to sleep...STATIC
Traceback (most recent call last):
File "py_instance.py", line 17, in <module>
print(Dog.sleep('Jerff').static_var)
AttributeError: 'NoneType' object has no attribute 'static_var'
"""

静态方法与中不存在调用关系

 # -*- coding:utf-8 -*-
# class Dog(object): def __init__(self, name):
self.name = name
print('self.name = %s' %self.name) @staticmethod
def sleep(self):
print('%s is going to sleep...' %self) Dog('Tim').sleep('Jerry')
print(Dog('Tim').sleep('Jerry') is Dog.sleep('Jerff')) ''' 再次证明类与静态方法无关
self.name = Tim
Jerry is going to sleep...
self.name = Tim
Jerry is going to sleep...
Jerff is going to sleep...
True
'''

静态方法与类

 # -*- coding:utf-8 -*-
# class Dog(object):
class_var = 'Hrrrrrrrrrrrrr......' def __init__(self, name):
self.name = name
print('self.name = %s' %self.name) @staticmethod
def sleep(self):
print('%s is going to sleep...' %self) class Animal(Dog):
def sleep(self):
print('%s is here...' %self.name)
print('static method can be overrided by subclass...') if __name__ == '__main__':
Dog('Tim').sleep('Jerry')
print(Dog('Tim').sleep('Jerry') is Dog.sleep('Jerff'))
print(Dog.class_var)
Dog.class_var = 'changed......'
print(Dog.class_var)
Animal('Jack').sleep() ''' 静态方法可以在子类中被重写
self.name = Tim
Jerry is going to sleep...
self.name = Tim
Jerry is going to sleep...
Jerff is going to sleep...
True
Hrrrrrrrrrrrrr......
changed......
self.name = Jack
Jack is here...
static method can be overrided by subclass...
'''

静态方法在子类中被重写

由以上两例可知:

静态方法仅在逻辑上隶属于类,与类变量性质相当;

静态方法与类变量一样,执行时只在代码区生成一份,类或多个类实例共享同一个静态方法,相较于实例方法,每生成一个实例,就必须生成一个对象,静态方法更加高效,节约资源;

静态方法在子类中可被重写,且重写的方法不一定是静态方法。

2.3 类方法

 # -*- coding:utf-8 -*-
#
class Dog(object): def __init__(self, name):
self.name = name
print('self.name = %s' %self.name) @classmethod
def sleep():
print('%s is going to sleep...' %self) print(Dog.sleep)
Dog.sleep() '''
与实例方法不一样,实例方法的绑定方法是Dog.sleep,类方法绑定的是type.sleep
<bound method type.sleep of <class '__main__.Dog'>> 类方法默认出入了一个类对象
Traceback (most recent call last):
File "py_instance.py", line 15, in <module>
Dog.sleep()
TypeError: sleep() takes no arguments (1 given)
'''

类方法绑定的是type类

 # -*- coding:utf-8 -*-
#
class Dog(object): def __init__(self, name):
self.name = name
print('self.name = %s' %self.name) @classmethod
def sleep(name):
print('%s is going to sleep...' %name) print(Dog.sleep)
Dog.sleep() ''' 类对象默认作为第一参数传入到类方法中
<bound method type.sleep of <class '__main__.Dog'>>
<class '__main__.Dog'> is going to sleep...
'''

类对象作为第一参数传入类方法中

 # -*- coding:utf-8 -*-
#
class Dog(object): name = 'Here' def __init__(self, name):
self.name = name
# print('self.name = %s' %self.name)
# print('self = ' %type(self)) @staticmethod
def talk():
return 'Animals and me' @classmethod
def sleep(cls):
print('%s is going to sleep...' %type(cls))
print('%s is going to sleep...' %cls.name)
print('%s are talking to each other...' %cls.talk()) print(Dog.sleep)
print(Dog.sleep is Dog.sleep)
Dog('Tim').sleep() ''' 类方法对类变量和静态方法的调用
<bound method type.sleep of <class '__main__.Dog'>>
False
<type 'type'> is going to sleep...
Here is going to sleep...
Animals and me are talking to each other...
'''

类方法可以引用类属性和静态方法

由上面的例子可知:

类方法的优点参考:http://www.cnblogs.com/ant-colonies/p/6736567.html

2.4 属性方法

属性方法的作用就是通过@property把一个方法变成一个静态属性。

class Dog(object):

    def __init__(self,name):
self.name = name @property
def eat(self):
print(" %s is eating" %self.name) d = Dog("ChenRonghua")
d.eat()

调用会出以下错误, 说NoneType is not callable, 因为eat此时已经变成一个静态属性了, 不是方法了, 想调用已经不需要加()号了,直接d.eat就可以了。

Tim is eating
Traceback (most recent call last):
File "py_11.py", line 12, in <module>
d.eat()
TypeError: 'NoneType' object is not callable

正确的调用如下:

d = Dog("ChenRonghua")
d.eat 输出
ChenRonghua is eating

好吧,把一个方法变成静态属性有什么卵用呢?既然想要静态变量,那直接定义成一个静态变量不就得了么?well, 以后你会需到很多场景是不能简单通过 定义 静态属性来实现的, 比如 ,你想知道一个航班当前的状态,是到达了、延迟了、取消了、还是已经飞走了, 想知道这种状态你必须经历以下几步:

1. 连接航空公司API查询

2. 对查询结果进行解析

3. 返回结果给你的用户

因此这个status属性的值是一系列动作后才得到的结果,所以你每次调用时,其实它都要经过一系列的动作才返回你结果,但这些动作过程不需要用户关心, 用户只需要调用这个属性就可以,明白 了么?

 # -*- coding:utf-8 -*-
#
class Flight(object):
def __init__(self, name):
self.flight_name = name
def checking_status(self):
print('checking flight %s status' %self.flight_name)
return 1 @property
def flight_status(self):
status = self.checking_status()
if status == 0:
print('flight got canceled...')
elif status == 1:
print('flight has arrived...')
elif status == 2:
print('flight has departured already...')
else:
print('cannot confirm the flight status, check it latter...') f = Flight('CA980')
f.flight_status '''
checking flight CA980 status
flight has arrived...
'''

flight_status

cool , 那现在我只能查询航班状态, 既然这个flight_status已经是个属性了, 那我能否给它赋值呢?试试吧

f = Flight("CA980")
f.flight_status
f.flight_status = 2

输出, 说不能更改这个属性,我擦。。。。,怎么办怎么办。。。

checking flight CA980 status
flight has arrived...
[root@ant-colonies tmp]# python py_flight.py
checking flight CA980 status
flight has arrived...
Traceback (most recent call last):
File "py_flight.py", line 24, in <module>
f.flight_status = 2
AttributeError: can't set attribute

当然可以改, 不过需要通过@proerty.setter装饰器再装饰一下,此时 你需要写一个新方法, 对这个flight_status进行更改。

 # -*- coding:utf-8 -*-
#
class Flight(object):
def __init__(self, name):
self.flight_name = name
def checking_status(self):
print('checking flight %s status' %self.flight_name)
return 1 @property
def flight_status(self):
status = self.checking_status()
if status == 0:
print('flight got canceled...')
elif status == 1:
print('flight has arrived...')
elif status == 2:
print('flight has departured already...')
else:
print('cannot confirm the flight status, check it latter...') @flight_status.setter # modify
def flight_status(self, status):
status_dic = {
0 : 'canceled',
1 : 'arrived',
2 : 'departured'
}
print('\033[31;1mHas changed the flight status to %s\033[0m' %status_dic.get(status)) @flight_status.deleter # delete
def flight_status(self):
print('status has been removed...') f = Flight('CA980')
f.flight_status
f.flight_status = 2 # trigger @flight_status.setter
del f.flight_status # trigger @flight_status.deleter

modify & delete properties

输出结果:

checking flight CA980 status
flight has arrived...
Has changed the flight status to departured
status has been removed...

注意以上代码里还写了一个@flight_status.deleter, 是允许可以将这个属性删除。

总结:

实例方法通过self访问实例属性

def instanceMethod(self, ...):

类方法通过cls方法访问类属性

@classmethod
def classMethod(cls, ...):

静态方法,不可访问,可以通过参数传值的方式进行

@staticmethod
def staticMethod(*agrs, **kwargs):

属性方法,不可访问,可修改属性和删除属性

@property
def propertyMethod(self, ...):
pass @propertyMethod.setter
def propertyMethod(self, ...):
pass @propertyMethod.deleter
def propertyMethod(self, ...):
pass

实例方法,当类实例化后,实例对象可以访问属性;

类方法,类对象和实例对象均可访问类属性;

静态方法,作用域为类中的方法,与类变量类似;

属性方法,当类实例化后,实例对象可以访问属性,将方法调用方式转变为类变量的访问方式。

3. 类的特殊成员方法

3.1  __doc__表示类的描述信息

# -*- coding:utf-8 -*-
# Author: antcolonies class Foo(object):
'''discription of the function of the Foo()''' def funct(self):
pass print(Foo.__doc__) 输出:
'''
discription of the function of the Foo()
'''

3.2  __module__ 和  __class__ 

  __module__ 表示当前操作的对象在那个模块

  __class__     表示当前操作的对象的类是什么

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies class C(object):
def __init__(self):
self.name = 'Monkey'

lib/aa.py

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies from lib.aa import C obj = C()
print(obj.__module__) # lib.aa
print(obj.__class__) # <class 'lib.aa.C'>

index.py

3.3  __init__ 构造方法,通过类创建对象时,自动触发执行。

3.4  __del__

 析构方法,当对象在内存中被释放时,自动触发执行。

注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,
因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的.

3.5  __call__ 对象后面加括号,触发执行

注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Foo(object):
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__') obj = Foo() # 执行__init__
obj() # 执行__call__

3.6. __dict__ 查看类或对象中的所有成员新式类__slots__内置属性对__dict__属性的消除作用

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies class Province(object):
country = 'China'
def __init__(self, name, count):
self.name = name
self.count = count
def func(self, *args, **kwargs):
print('func') # 获取类成员,即:静态字段、方法
print(Province.__dict__)
# {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Province' objects>,
# '__doc__': None, 'country': 'China', 'func': <function Province.func at 0x00000000027ECA60>,
# '__init__': <function Province.__init__ at 0x00000000027EC8C8>, '__weakref__': <attribute '__weakref__' of 'Province' objects>} # 获取对象obj_1的成员
obj_1 = Province('Hebei', 10000)
print(obj_1.__dict__)
# {'name': 'Hebei', 'count': 10000} # 获取对象obj_2的成员
obj_2 = Province('Henan', 30009)
print(obj_2.__dict__)
# {'name': 'Henan', 'count': 30009}

3.7  __str__ ,如果一个类中定义了__str__方法,那么在打印实例化对象时,默认输出该__str__方法的返回值。

class Foo(object):
def method(self):
print('----------') def __str__(self):
return 'Alex Lee' obj = Foo()
print(obj) '''Alex Lee'''

3.8  __getitem__、__setitem__、__delitem__

用于索引操作,如字典。以上分别表示获取、设置、删除数据

# -*- coding:utf-8 -*-
# Author: antcolonies class Foo(object):
def __getitem__(self, item):
print('__getitem', item) def __setitem__(self, key, value):
print('__setitem__',key, value) def __delitem__(self, key):
print('__delitem__', key) obj = Foo() result = obj['k1'] # trigger and run __getitem__
obj['k2'] = 'alex' # trigger and run __settitem__
del obj['k1'] '''
__getitem k1
__setitem__ k2 alex
__delitem__ k1
'''

3.9  __new__ \ __metaclass__

参考: http://www.cnblogs.com/ant-colonies/p/6747309.html

http://www.cnblogs.com/ant-colonies/p/6748064.html

类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__

4. 反射

参考:http://www.cnblogs.com/ant-colonies/p/6756014.html

http://www.cnblogs.com/ant-colonies/p/6758266.html

5. 异常处理

5.1 异常基础

在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是出现一个提示的页面。

try:
pass
except Exception as e:
pass

需求:将用户输入的两个数字相加

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies while True:
num_1 = input('num_1: ')
num_2 = input('num_2: ')
try:
num_1 = int(num_1)
num_2 = int(num_2)
result = num_1 + num_2
except Exception as e:
print('error message: %s' %e)

exception

5.2 异常的种类

python中的异常种类非常多,每个异常专门用于处理某一项异常。

 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
FileNotFoundError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的

常见异常类型

 ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

更多异常类型

 dic = ['Tim', 'Cook']
try:
dic[10]
except IndexError as e:
print('error message: %s' %e)

实例:IndexError

 dic = {'k1':'v1'}
try:
dic['k2']
except KeyError as e:
print('error message: %s' %e)

实例:KeyError

 s1 = 'Hello'
try:
int(s1)
except ValueError as e:
print('error message: %s' %e)

实例:ValueError

对于上述实例,异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。

# 未捕获到异常,程序直接报错

s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)

所以,写程序时需要考虑到try代码块中可能出现的任意异常,可以这样写:

s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)

在python的异常中,有一个万能异常:Exception,他可以捕获任意异常,即:

s1 = 'hello'
try:
int(s1)
except Exception as e:
print(e)

接下来你可能要问了,既然有这个万能异常,其他异常是不是就可以忽略了!

答:当然不是,对于特殊处理或提醒的异常需要先定义,最后定义Exception来确保程序正常运行。

s1 = 'hello'
try:
int(s1)
except KeyError as e:
print('键错误')
except IndexError as e:
print('索引错误')
except Exception as e:
print('错误')

5.3 异常的其他结构

try:
# 主代码块
pass
except KeyError as e:
# 异常时,执行该块
pass
else:
# 主代码块执行完,执行该块
pass
finally:
# 无论异常与否,最终执行该块
pass
 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies names = ['alex', 'jack']
data = {} try:
names[3]
data['name']
open('test.tc')
names[1]
except FileNotFoundError as e:
print(e)
except KeyError as e:
print('%s does not exist' %e)
except IndexError as e:
print(e)
# except (IndexError,KeyError) as e: 不同错误的相同处理方式
# print(e)
except Exception as e: # 抓取所有错误,一般用于错误抓取末尾
print('all error can be catched %s' %e)
else:
print('all things are okay now!')
finally:
print('all can be done, no matter what runs wrong')

实例

5.5 自定义异常

class CustomizeError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg try:
name = []
raise CustomizeError('Database Connection error.. ')
except CustomizeError as e:
print(e)
 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: antcolonies class IndexError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg try:
name = []
# name[3]
raise IndexError('Database Connection error.. ')
except IndexError as e:
print(e)

重载系统默认错误类型

5.6 断言(assert)

在开发一个程序时候,与其让它运行时崩溃,不如在它出现错误条件时就崩溃(返回错误)。这时候断言assert 就显得非常有用。

assert的语法格式:

assert expression

它的等价语句为:

if not expression:
raise AssertionError

这段代码用来检测数据类型的断言,因为 a_strstr 类型,所以认为它是 int 类型肯定会引发错误。

>>> a_str = 'this is a string'
>>> type(a_str)
<type 'str'>
>>> assert type(a_str)== str
>>> assert type(a_str)== int Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
assert type(a_str)== int
AssertionError

参考: http://www.cnblogs.com/wupeiqi/p/4493506.html

http://www.cnblogs.com/wupeiqi/p/4766801.html

day07 - Python - 面向对象进阶的更多相关文章

  1. Python面向对象进阶(二)

    Python面向对象进阶2.html :first-child{margin-top:0!important}img.plugin{box-shadow:0 1px 3px rgba(0,0,0,.1 ...

  2. Python开发【第七篇】:面向对象 和 python面向对象进阶篇(下)

    Python开发[第七篇]:面向对象   详见:<Python之路[第五篇]:面向对象及相关> python 面向对象(进阶篇)   上一篇<Python 面向对象(初级篇)> ...

  3. Python面向对象进阶和socket网络编程-day08

    写在前面 上课第八天,打卡: 为什么坚持?想一想当初: 一.面向对象进阶 - 1.反射补充 - 通过字符串去操作一个对象的属性,称之为反射: - 示例1: class Chinese: def __i ...

  4. Python面向对象进阶和socket网络编程

    写在前面 为什么坚持?想一想当初: 一.面向对象进阶 - 1.反射补充 - 通过字符串去操作一个对象的属性,称之为反射: - 示例1: class Chinese: def __init__(self ...

  5. python面向对象进阶(八)

    上一篇<Python 面向对象初级(七)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...

  6. python面向对象进阶

    前言 上节大话python面向对象对面向对象有了一些了解,这次就不用大话风格了 (ps:真心不好扯啊) isinstance与issubclass isinstance(obj,cls)检查是否obj ...

  7. python 面向对象进阶之内置方法

    一 isinstance(obj,cls)和issubclass(sub,super) 1.1,isinstance(obj,cls)检查是否obj是否是类 cls 的对象 class Foo(obj ...

  8. Python 面向对象 (进阶篇)

    <Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使用(可 ...

  9. Python之路-python(面向对象进阶)

    一.面向对象高级语法部分 1.静态方法.类方法.属性方法 2.类的特殊方法 3.反射 二.异常处理 三.Socket开发基础 一.面向对象高级语法部分 静态方法(@staticmethod) 定义:只 ...

随机推荐

  1. db2 中 SQL判断物理表是否存在、修改表名

    1.db2 中 SQL判断物理表是否存在 SELECT * FROM SYSIBM.SYSTABLES WHERE TID <> 0 AND Name = 'TABLE_NAME' AND ...

  2. C#ThreadPool学习

    一.简介 提供一个线程池,该线程池可用于执行任务.发送工作项.处理异步 I/O.代表其他线程等待以及处理计时器 注意:线程池中启动的线程都是后台线程 二.主要方法 GetAvailableThread ...

  3. 【C#】MVC+EF+LINQ 综合小项目

    第一,创建数据库 create table category(id int primary key,name nvarchar(20)) create table news(id int primar ...

  4. SQL Server乱码处理(ASCII)

    CREATE FUNCTION [dbo].[RegexReplace] ( @string VARCHAR(MAX), --被替换的字符串 @pattern VARCHAR(255), --替换模板 ...

  5. Django 实现上传图片功能

    很多时候我们要用到图片上传功能,如果图片一直用放在别的网站上,通过加载网址的方式来显示的话其实也挺麻烦的,我们通过使用 django-filer 这个模块实现将图片文件直接放在自己的网站上. 感兴趣的 ...

  6. 【ARC077F】SS kmp+打表找规律

    Description ​ 如果某个串可以由两个一样的串前后连接得到,我们就称之为"偶串".比如说"xyzxyz"和"aaaaaa"是偶串, ...

  7. 【guava】对象处理

    一,equals方法 我们在开发中经常会需要比较两个对象是否相等,这时候我们需要考虑比较的两个对象是否为null,然后再调用equals方法来比较是否相等,google guava库的com.goog ...

  8. 运行Scrapy工程,报错ModuleNotFoundError: No module named 'win32api'解决方法

    1.运行爬虫scrapy crawl name,报错ScrpyModuleNotFoundError: No module named 'win32api' 2.解决方法: 在https://gith ...

  9. Cygwin apt-cyg ”MD5 sum did not match”

    直接编辑apt-cyg 文件,找到md5sum,替换修改成sha512sum. # check the md5 digest=`cat "desc" | awk '/^instal ...

  10. SHELL编程之case与函数

    一.case语句概述 使用case语句改写if多分支可以使脚本结构更加清晰.层次分明 针对变量不同取值,执行不同的命令序列 case语句结构如下: case 变量值  in 模式1) 命令序列1 ;; ...