pythonwithclass
❶ 如何在python中使用static,class,abstract方法
class 方法直接写
static方法在方法前加上@staticmethod
abstract方法先从abc导入
from abc import abstractmethod
然后在方法前加上@abstractmethod
❷ Python中的with...as用法介绍
这篇文章主要介绍了Python中的with...as用法介绍,本文直接给出用法实例,需要的朋友可以参考下
这个语法是用来代替传统的try...finally语法的。
代码如下:
with
EXPRESSION
[
as
VARIABLE]
WITH-BLOCK
基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。
代码如下:
file
=
open("/tmp/foo.txt")
try:
data
=
file.read()
finally:
file.close()
使用with...as...的方式替换,修改后的代码是:
代码如下:
with
open("/tmp/foo.txt")
as
file:
data
=
file.read()
#!/usr/bin/env
python
#
with_example01.py
class
Sample:
def
__enter__(self):
print
"In
__enter__()"
return
"Foo"
def
__exit__(self,
type,
value,
trace):
print
"In
__exit__()"
def
get_sample():
return
Sample()
with
get_sample()
as
sample:
print
"sample:",
sample
执行结果为
代码如下:
In
__enter__()
sample:
Foo
In
__exit__()
1.
__enter__()方法被执行
2.
__enter__()方法返回的值
-
这个例子中是"Foo",赋值给变量'sample'
3.
执行代码块,打印变量"sample"的值为
"Foo"
4.
__exit__()方法被调用with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数-
val,
type
和
trace。这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。
❸ Python如何调用自定义类中的函数
定义一个函数只给了函数一个名称,指定了函数里包含的参数,和代码块结构。版这个函数的基本结构完成权以后,你可以通过另一个函数调用执行,也可以直接从Python提示符执行。
如下实例调用了printme()函数:
复制代码 代码如下:#!/usr/bin/python
# Function definition is here
def printme( str ):
"打印任何传入的字符串"
print str;
return;
# Now you can call printme function
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");
#以上实例输出结果:
#我要调用用户自定义函数!
#再次调用同一函数
❹ python中with python中with as 是什么意思刚入门求解释!!!
这个语法是用来代替传统的try...finally语法的。
with EXPRESSION [ as VARIABLE] WITH-BLOCK
基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。
file=open("/tmp/foo.txt")
try:
data=file.read()
finally:
file.close()
使用with...as...的方式替换,修改后的代码是:
withopen("/tmp/foo.txt")asfile:
data=file.read()
#!/usr/bin/envpython
#with_example01.py
classSample:
def__enter__(self):
print"In__enter__()"
return"Foo"
def__exit__(self,type,value,trace):
print"In__exit__()"
defget_sample():
returnSample()
withget_sample()assample:
print"sample:",sample
执行结果为
In__enter__()
sample:Foo
In__exit__()
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是"Foo",赋值给变量'sample'
3. 执行代码块,打印变量"sample"的值为 "Foo"
4. __exit__()方法被调用with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。这些参数在异常处理中相当有用。
请点赞!
❺ 请教几个python语法题
# 7
class Myclass():
@classmethod # 这个装饰器是专门供类使用的方法
def class_say_hello(cls, s):
print("class method", s)
Myclass.class_say_hello("NEU2")
# 8
def myrepr(cls):
cls.__repr__ = lambda self: super(cls, self).__repr__()[10:15]
return cls
@myrepr
class classwithlonglonglongname(): pass
c = classwithlonglonglongname()
print(c)
# 13
class A: pass
a = A()
print(isinstance(a, A), isinstance(A, object))
# 14
def mymethod(self):
return "hello in mumethod"
klass = type("Myclass", (object,), {'method': mymethod})
inst = klass()
print(inst.method())
❻ 在Python中怎么把class类转成list类
你需要自定义函数。
或者使用__list__,这样就可以使用内置的list函数了。专
classA:
def__init__():
self.a=1
self.b=2
defto_list():
"""需要你自属定义函数行为"""
return[self.a,self.b]
def__list__():
"""需要你自定义函数行为"""
return[self.a,self.b]
a=A()
lst1=a.to_list()
lst2=list(a)#调用__list__
别的可以直接调用list函数的都是底层实现了__list__或者做了别的实现,你自己的类需要你自己实现。
❼ 怎么判断一个变量是不是类 python
python中如何判断一个变量的数据类型?(原创) 收藏
import types
type(x) is types.IntType # 判断是否 类型
type(x) is types.StringType #是否string类型
.........
--------------------------------------------------------
超级恶心的模式,不用记住types.StringType
import types
type(x) == types(1) # 判断是否int 类型
type(x) == type('a') #是否string类型
------------------------------------------------------
使用内嵌函数:
isinstance ( object, classinfo )
Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object and object is an object of that type. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Changed in version 2.2: Support for a tuple of type information was added.
Python可以得到一个对象的类型 ,利用type函数:
>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>
不仅如此,还可以利用isinstance函数,来判断一个对象是否是一个已知的类型。
isinstance说明如下:
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。
>>>isinstance(lst, list)
Trueisinstance(lst, (int, str, list))
True
>>>isinstance(lst, (int, str, list))
True
❽ python 3 有关class 的问题 急!!!
if self.login(entered_password):
self.account_info = new_info
❾ python中with是什么意思
关键字
with 的一般执行过程
一段基本的 with 表达式,其结构是这样的:
with EXPR as VAR:
BLOCK
其中: EXPR 可以是任意表达式; as VAR 是可选的。
❿ python的关键字有哪些,都是什么意思
我这里汇总经常用到的27个关键字,希望对正在学Python的你能够起到帮助
1 and:逻辑与
2 as:为导入的模块取一个别名,在Python2.6中新增
3 assert:断言,在Python1.5新增
4 break:用在循环语句,跳转到语句块的末尾
5 class:用来定义一个类
6 continue:和break香对应,跳到语句块的开头
7 def:用来定义一个函数或方法
8 del:删除
9 elif:全称是else if
10 exec:内置函数。执行以string类型存储的Python代码
11 finally:用在异常处理语句try-excep-finally中
12 for:著名的for循环,可以用来遍历一个列表
13 from:字面意思,表示从一个包导入某个模块
14 global:在函数或其他局部作用域中使用全局变量
15 if:如果
16 import:导入
17 in:在,后面跟一个列表,字典或字符串
18 is:逻辑判断
19 not:逻辑非
20 or:逻辑或
21 pass:占位符,用来告诉Python这里不用考虑
22 print:写得最多的关键字,后来在Python3.0中变成了内置函数
23 raise:用来引发一个异常
24 return:函数返回
25 try:异常处理机制
26 while:while循环
27 with:在Python2.6中新增,使用with候不管with中的代码出现什么错误,都会进行对当前对象进行清理工作,注意该句话后面有一个冒号表示with语句。
以上就是我汇总的部分关键字,希望对你有所帮助