1
class MyClass:def __init__(self):print("Constructor called.")def __str__(self):return "MyClass instance"obj = MyClass()print(obj) # 调用__str__方法
在Python中,__str__
是一个特殊的方法,当你使用print()
函数打印一个对象时,Python会自动调用这个对象的__str__
方法来获取一个字符串表示。如果一个类定义了__str__
方法,那么当你打印这个类的实例时,就会输出这个方法返回的字符串。
在你提供的代码中,MyClass
类定义了一个__str__
方法,这个方法返回一个字符串"MyClass instance"
。当你创建了一个MyClass
的实例obj
并打印它时,Python会调用这个__str__
方法,所以输出将会是:
2.多行操作
item_one=1
item_two=2
item_three=3total=item_one+\item_two+\item_threeprint (total)
3. 换行输出
#!/usr/bin/python
# -*- coding: UTF-8 -*-x="a"
y="b"
# 换行输出
print (x)
print (y)#p3 输出 , p逗号表示不换行,p3 end=''
print ('---------',end='')
# 不换行输出
print (x,end='')
print (y,end='')# 不换行输出
print (x+y)
4
➜ PythonGuide python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options (and corresponding environment variables):
-b : issue warnings about converting bytes/bytearray to str and comparingbytes/bytearray with str or bytes with int. (-bb: issue errors)
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : turn on parser debugging output (for experts only, only works ondebug builds); also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also -? or --help)
-i : inspect interactively after running script; forces a prompt evenif stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and __debug__-dependent statements; add .opt-1 before.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before.pyc extension
-P : don't prepend a potentially unsafe path to sys.path; alsoPYTHONSAFEPATH
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x
-S : don't imply 'import site' on initialization
-u : force the stdout and stderr streams to be unbuffered;this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=xcan be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:linenoalso PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
--check-hash-based-pycs always|default|never:control how Python invalidates hash-based .pyc files
--help-env: print help about Python environment variables and exit
--help-xoptions: print help about implementation-specific -X options and exit
--help-all: print complete help information and exitArguments:
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
➜ PythonGuide python -c "print('Hello, World!')"
Hello, World!
➜ PythonGuide
-
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
:这一行说明了 Python 解释器的基本用法,它可以接受一系列的选项(option)和参数(arg)。选项前面有一个破折号(-),参数则直接跟在选项后面或者在文件名(file)后面。 -
-c cmd
:表示可以将一个 Python 代码字符串作为命令行参数传递给解释器执行。例如:python -c "print('Hello, World!')"
。 -
-d
:启用调试输出模式,这有助于开发者查看解析器的内部工作过程。 -
-E
:忽略环境变量,例如PYTHONPATH
。这意味着 Python 解释器将不会使用任何环境变量来查找模块或文件。 -
-h
:打印帮助信息并退出。这是最常用的选项之一,当你需要了解如何使用 Python 解释器时,可以使用这个选项。
帮助信息的最后还提到了其他一些选项,如 -i
(在执行脚本后进入交互模式)、-v
(输出详细信息)等。这些选项可以根据需要组合使用,以满足不同的编程需求。
例如,如果你想执行一个 Python 脚本并且忽略任何环境变量的影响,你可以这样输入:
shellscript
- Run
python -E my_script.py
这段帮助信息对于初学者和有经验的开发者都非常有用,它提供了一个快速参考,帮助你了解如何正确地使用 Python 解释器。
5. 字典
#!/usr/bin/python
# -*- coding: UTF-8 -*-dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"tinydict = {'name': 'runoob','code':6734, 'dept': 'sales'}print dict['one'] # 输出键为'one' 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值
6.
数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。
以下几个内置的函数可以执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。
函数 | 描述 |
---|---|
int(x [,base]) | 将x转换为一个整数 |
long(x [,base] ) | 将x转换为一个长整数 |
float(x) | 将x转换到一个浮点数 |
complex(real [,imag]) | 创建一个复数 |
str(x) | 将对象 x 转换为字符串 |
repr(x) | 将对象 x 转换为表达式字符串 |
eval(str) | 用来计算在字符串中的有效Python表达式,并返回一个对象 |
tuple(s) | 将序列 s 转换为一个元组 |
list(s) | 将序列 s 转换为一个列表 |
set(s) | 转换为可变集合 |
dict(d) | 创建一个字典。d 必须是一个序列 (key,value)元组。 |
frozenset(s) | 转换为不可变集合 |
chr(x) | 将一个整数转换为一个字符 |
unichr(x) | 将一个整数转换为Unicode字符 |
ord(x) | 将一个字符转换为它的整数值 |
hex(x) | 将一个整数转换为一个十六进制字符串 |
oct(x) | 将一个整数转换为一个八进制字符串 |
7.
//取整除 - 返回商的整数部分(向下取整)
>>> 9//2 4 >>> -9//2 -5
# 修改变量 a 、b 、c
a = 2
b = 3
c = a**b
print "6 - c 的值为:", ca = 10
b = 5
c = a//b
print "7 - c 的值为:", c
8.
Python位运算符
按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如下:
下表中变量 a 为 60,b 为 13,二进制格式如下:
a = 0011 1100b = 0000 1101-----------------a&b = 0000 1100a|b = 0011 1101a^b = 0011 0001~a = 1100 0011
Python逻辑运算符
if not( a and b ): print "5 - 变量 a 和 b 都为 False,或其中一个变量为 False" else: print "5 - 变量 a 和 b 都为 True"
Python成员运算符
#!/usr/bin/python
# -*- coding: UTF-8 -*-a = 10
b = 20
list = [1, 2, 3, 4, 5 ];if ( a in list ):print "1 - 变量 a 在给定的列表中 list 中"
else:print "1 - 变量 a 不在给定的列表中 list 中"if ( b not in list ):print "2 - 变量 b 不在给定的列表中 list 中"
else:print "2 - 变量 b 在给定的列表中 list 中"# 修改变量 a 的值
a = 2
if ( a in list ):print "3 - 变量 a 在给定的列表中 list 中"
else:print "3 - 变量 a 不在给定的列表中 list 中"
Python身份运算符
身份运算符用于比较两个对象的存储单元
运算符 | 描述 | 实例 |
---|---|---|
is | is 是判断两个标识符是不是引用自一个对象 | x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False |
is not | is not 是判断两个标识符是不是引用自不同对象 | x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-a = 20
b = 20if ( a is b ):print "1 - a 和 b 有相同的标识"
else:print "1 - a 和 b 没有相同的标识"if ( a is not b ):print "2 - a 和 b 没有相同的标识"
else:print "2 - a 和 b 有相同的标识"# 修改变量 b 的值
b = 30
if ( a is b ):print "3 - a 和 b 有相同的标识"
else:print "3 - a 和 b 没有相同的标识"if ( a is not b ):print "4 - a 和 b 没有相同的标识"
else:print "4 - a 和 b 有相同的标识"
why
在Python中,is
和==
是两种不同的比较操作符。
is
操作符用于比较两个对象的身份(即它们是否是同一个对象)。如果两个对象是同一个对象,那么is
操作符返回True
,否则返回False
。==
操作符用于比较两个对象的值(即它们是否包含相同的数据)。如果两个对象的值相等,那么==
操作符返回True
,否则返回False
。
在你的例子中:
b = a
使得b
和a
指向同一个列表对象,所以b is a
返回True
,并且b == a
也返回True
。b = a[:]
创建了一个新的列表对象b
,它包含与a
相同的元素,但它们是不同的对象。所以b is a
返回False
,但是b == a
仍然返回True
,因为它们包含相同的值。
总结一下,is
比较的是对象的身份,而==
比较的是对象的值。在Python中,理解这两个操作符的区别是非常重要的
简单的语句组
实例
#!/usr/bin/python # -*- coding: UTF-8 -*- var = 100 if ( var == 100 ) : print "变量 var 的值为100" print "Good bye!"
以上代码执行输出结果如下:
变量 var 的值为100 Good bye!