Python学习第二天
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习第二天相关的知识,希望对你有一定的参考价值。
我们为什么学习Python呢?为什么是Python而不是其他语言呢?
C和Python、java、C#等
C语言:代码编译得到机器码,机器码在处理上直接执行,每一条指令控制CPU工作。
其他语言:代码编译得到字节码,虚拟机执行字节码转换成机器码再在处理器上执行
Python和CPython:这门语言是由C开发而来
对于使用:Python的类库齐全并且使用简洁,如果要实现同样的功能,Python 10行代码可以解决,C可能就需要100行甚至更多。
对于速度:Python的运行速度相较于C,是慢了。
Python和Java、C#等
对于使用:Linux原装Python,其他语言没有,以上几门语言都有非常丰富的类库支持
对于速度:Python在速度上可能稍显逊色
所以,Python和其他语言没有什么本质区别,其他区别在于,擅长某领域、人才丰富、先入为主。
那么Python的种类有哪些呢?
这里我们举几个Python的几个种类:
cPython 比如打印‘alex’时, print(‘alex’) c解释器解释成 .pyc(字节码)-> 机器码 cpu
jPython print(‘alex’) java解释器解释成 java(字节码)-> 机器码 cpu
ironPython print(‘alex’) c#解释器解释成 c#(字节码)-> 机器码 cpu
也就是它们运行的内部原理是不同的。
老师说pypy早晚会火的啊!这是因为它在编译的时候就生成了机器码。
.pyc文件
执行Python代码时,如果导入了其他的.py文件,那么,执行过程中会自动生成一个与其同名的.pyc文件,该文件就是Python解释器编译之后的字节码。
代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。
例子:建两个文件 index.py和lib.py 首先在lib里print(‘lib’)
在index里
import lib
print(‘index’) 这个时候就产生了lib.pyc文件!
基本的数据类型:(这是重点哦!)
因此str是类,int是类,dict、list、tuple等等都是类。
“guojingjing”、99、{‘北京‘,‘上海‘,‘广州‘,‘深圳‘}是分别根据str类、int类和dict类生成的。
在这里介绍2种查看类中成员的方法:1、首先,需要装python,然后至少要有个命令行窗口:dir(类名)2、在Pycharm中输入类名比如str,左手按住ctrl键的同时鼠标变成小手时点击该类名就可以了。
对于方法1(这里以类str为例)其结果是:
对于方法2(这里以类str为例)其结果是:
class str(object): """ str(object=‘‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict‘. """ def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return "" def casefold(self): # real signature unknown; restored from __doc__ """ S.casefold() -> str Return a version of S suitable for caseless comparisons. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def encode(self, encoding=‘utf-8‘, errors=‘strict‘): # real signature unknown; restored from __doc__ """ S.encode(encoding=‘utf-8‘, errors=‘strict‘) -> bytes Encode S using the codec registered for encoding. Default encoding is ‘utf-8‘. errors may be given to set a different error handling scheme. Default is ‘strict‘ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore‘, ‘replace‘ and ‘xmlcharrefreplace‘ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return b"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ """ S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(*args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> str Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{‘ and ‘}‘). """ pass def format_map(self, mapping): # real signature unknown; restored from __doc__ """ S.format_map(mapping) -> str Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{‘ and ‘}‘). """ return "" def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def isidentifier(self): # real signature unknown; restored from __doc__ """ S.isidentifier() -> bool Return True if S is a valid identifier according to the language definition. Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ return False def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return False def isprintable(self): # real signature unknown; restored from __doc__ """ S.isprintable() -> bool Return True if all characters in S are considered printable in repr() or S is empty, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def maketrans(self, *args, **kwargs): # real signature unknown """ Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. """ pass def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub[, start[, end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub[, start[, end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.rsplit(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=None): # real signature unknown; restored from __doc__ """ S.splitlines([keepends]) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return "" def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> str Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> str Return a copy of S converted to uppercase. """ return "" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return "" def __add__(self, *args, **kwargs): # real signature unknown """ Return self+value. """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> str Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, *args, **kwargs): # real signature unknown """ Return self[key]. """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init__(self, value=‘‘, encoding=None, errors=‘strict‘): # known special case of str.__init__ """ str(object=‘‘) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict‘. # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass def __mod__(self, *args, **kwargs): # real signature unknown """ Return self%value. """ pass def __mul__(self, *args, **kwargs): # real signature unknown """ Return self*value.n """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __rmod__(self, *args, **kwargs): # real signature unknown """ Return value%self. """ pass def __rmul__(self, *args, **kwargs): # real signature unknown """ Return self*value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass
在python中,还有一个“help(类名.方法名)”方法:可以查看类的详细功能;“help(类名.功能名)”:查看类中某功能的详细情况
>>> help(str) Help on class str in module __builtin__: class str(basestring) | str(object=‘‘) -> string | | Return a nice string representation of the object. | If the argument is a string, the return value is the same object. | | Method resolution order: | str | basestring | object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __eq__(...) | x.__eq__(y) <==> x==y | | __format__(...) | S.__format__(format_spec) -> string | | Return a formatted version of S as described by format_spec. | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__(‘name‘) <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getnewargs__(...) | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __mod__(...) | x.__mod__(y) <==> x%y | | __mul__(...) | x.__mul__(n) <==> x*n | | __ne__(...) | x.__ne__(y) <==> x!=y | | __repr__(...) | x.__repr__() <==> repr(x) | | __rmod__(...) | x.__rmod__(y) <==> y%x | | __rmul__(...) | x.__rmul__(n) <==> n*x | | __sizeof__(...) | S.__sizeof__() -> size of S in memory, in bytes | | __str__(...) | x.__str__() <==> str(x) | | capitalize(...) | S.capitalize() -> string | | Return a copy of the string S with only its first character | capitalized. | | center(...) | S.center(width[, fillchar]) -> string | | Return S centered in a string of length width. Padding is | done using the specified fill character (default is a space) | | count(...) | S.count(sub[, start[, end]]) -> int | | Return the number of non-overlapping occurrences of substring sub in | string S[start:end]. Optional arguments start and end are interpreted | as in slice notation. | | decode(...) | S.decode([encoding[,errors]]) -> object | | Decodes S using the codec registered for encoding. encoding defaults | to the default encoding. errors may be given to set a different error | handling scheme. Default is ‘strict‘ meaning that encoding errors raise | a UnicodeDecodeError. Other possible values are ‘ignore‘ and ‘replace‘ | as well as any other name registered with codecs.register_error that is | able to handle UnicodeDecodeErrors. | | encode(...) | S.encode([encoding[,errors]]) -> object | | Encodes S using the codec registered for encoding. encoding defaults | to the default encoding. errors may be given to set a different error | handling scheme. Default is ‘strict‘ meaning that encoding errors raise | a UnicodeEncodeError. Other possible values are ‘ignore‘, ‘replace‘ and | ‘xmlcharrefreplace‘ as well as any other name registered with | codecs.register_error that is able to handle UnicodeEncodeErrors. | | endswith(...) | S.endswith(suffix[, start[, end]]) -> bool | | Return True if S ends with the specified suffix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | suffix can also be a tuple of strings to try. | | expandtabs(...) | S.expandtabs([tabsize]) -> string | | Return a copy of S where all tab characters are expanded using spaces. | If tabsize is not given, a tab size of 8 characters is assumed. | | find(...) | S.find(sub [,start [,end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | format(...) | S.format(*args, **kwargs) -> string | | Return a formatted version of S, using substitutions from args and kwargs. | The substitutions are identified by braces (‘{‘ and ‘}‘). | | index(...) | S.index(sub [,start [,end]]) -> int | | Like S.find() but raise ValueError when the substring is not found. | | isalnum(...) | S.isalnum() -> bool | | Return True if all characters in S are alphanumeric | and there is at least one character in S, False otherwise. | | isalpha(...) | S.isalpha() -> bool | | Return True if all characters in S are alphabetic | and there is at least one character in S, False otherwise. | | isdigit(...) | S.isdigit() -> bool | | Return True if all characters in S are digits | and there is at least one character in S, False otherwise. | | islower(...) | S.islower() -> bool | | Return True if all cased characters in S are lowercase and there is | at least one cased character in S, False otherwise. | | isspace(...) | S.isspace() -> bool | | Return True if all characters in S are whitespace | and there is at least one character in S, False otherwise. | | istitle(...) | S.istitle() -> bool | | Return True if S is a titlecased string and there is at least one | character in S, i.e. uppercase characters may only follow uncased | characters and lowercase characters only cased ones. Return False | otherwise. | | isupper(...) | S.isupper() -> bool | | Return True if all cased characters in S are uppercase and there is | at least one cased character in S, False otherwise. | | join(...) | S.join(iterable) -> string | | Return a string which is the concatenation of the strings in the | iterable. The separator between elements is S. | | ljust(...) | S.ljust(width[, fillchar]) -> string | | Return S left-justified in a string of length width. Padding is | done using the specified fill character (default is a space). | | lower(...) | S.lower() -> string | | Return a copy of the string S converted to lowercase. | | lstrip(...) | S.lstrip([chars]) -> string or unicode | | Return a copy of the string S with leading whitespace removed. | If chars is given and not None, remove characters in chars instead. | If chars is unicode, S will be converted to unicode before stripping | | partition(...) | S.partition(sep) -> (head, sep, tail) | | Search for the separator sep in S, and return the part before it, | the separator itself, and the part after it. If the separator is not | found, return S and two empty strings. | | replace(...) | S.replace(old, new[, count]) -> string | | Return a copy of string S with all occurrences of substring | old replaced by new. If the optional argument count is | given, only the first count occurrences are replaced. | | rfind(...) | S.rfind(sub [,start [,end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | rindex(...) | S.rindex(sub [,start [,end]]) -> int | | Like S.rfind() but raise ValueError when the substring is not found. | | rjust(...) | S.rjust(width[, fillchar]) -> string | | Return S right-justified in a string of length width. Padding is | done using the specified fill character (default is a space) | | rpartition(...) | S.rpartition(sep) -> (head, sep, tail) | | Search for the separator sep in S, starting at the end of S, and return | the part before it, the separator itself, and the part after it. If the | separator is not found, return two empty strings and S. | | rsplit(...) | S.rsplit([sep [,maxsplit]]) -> list of strings | | Return a list of the words in the string S, using sep as the | delimiter string, starting at the end of the string and working | to the front. If maxsplit is given, at most maxsplit splits are | done. If sep is not specified or is None, any whitespace string | is a separator. | | rstrip(...) | S.rstrip([chars]) -> string or unicode | | Return a copy of the string S with trailing whitespace removed. | If chars is given and not None, remove characters in chars instead. | If chars is unicode, S will be converted to unicode before stripping | | split(...) | S.split([sep [,maxsplit]]) -> list of strings | | Return a list of the words in the string S, using sep as the | delimiter string. If maxsplit is given, at most maxsplit | splits are done. If sep is not specified or is None, any | whitespace string is a separator and empty strings are removed | from the result. | | splitlines(...) | S.splitlines(keepends=False) -> list of strings | | Return a list of the lines in S, breaking at line boundaries. | Line breaks are not included in the resulting list unless keepends | is given and true. | | startswith(...) | S.startswith(prefix[, start[, end]]) -> bool | | Return True if S starts with the specified prefix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | prefix can also be a tuple of strings to try. | | strip(...) | S.strip([chars]) -> string or unicode | | Return a copy of the string S with leading and trailing | whitespace removed. | If chars is given and not None, remove characters in chars instead. | If chars is unicode, S will be converted to unicode before stripping | | swapcase(...) | S.swapcase() -> string | | Return a copy of the string S with uppercase characters | converted to lowercase and vice versa. | | title(...) | S.title() -> string | | Return a titlecased version of S, i.e. words start with uppercase | characters, all remaining cased characters have lowercase. | | translate(...) | S.translate(table [,deletechars]) -> string | | Return a copy of the string S, where all characters occurring | in the optional argument deletechars are removed, and the | remaining characters have been mapped through the given | translation table, which must be a string of length 256 or None. | If the table argument is None, no translation is applied and | the operation simply removes the characters in deletechars. | | upper(...) | S.upper() -> string | | Return a copy of the string S converted to uppercase. | | zfill(...) | S.zfill(width) -> string | | Pad a numeric string S with zeros on the left, to fill a field | of the specified width. The string S is never truncated. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T
其他的类都可以用同样的方法查看其包含的成员,并且可以查看类中某成员的功能。
一、整数
其具备的功能:
其源码为:
class int(object): """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100‘, base=0) 4 """ def bit_length(self): # real signature unknown; restored from __doc__ """返回表示该数字时所用的最小位数 int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) ‘0b100101‘ >>> (37).bit_length() 6 """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """返回一个复数的共轭复数 Returns self, the complex conjugate of any int. """ pass def __abs__(self): # real signature unknown; restored from __doc__ """ 返回绝对值 x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ 返回两个数的和 x.__add__(y) <==> x+y """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ 返回两个数按位与的结果 x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """返回两个数比较的结果,参数从左至右(a,b),a>b返回1,a<b返回-1,a=b返回0 x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """a.__coerce__(b),强制返回一个元组(a,b) x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ 相除,得到商和余数组成的元组 x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """返回两数相除的商 x.__div__(y) <==> x/y """ pass def __float__(self): # real signature unknown; restored from __doc__ """将数据类型强制转换为float x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ 不保留小数点后的小数除法,也可以用‘//’来表示:a//b,我们亲切地称之为“地板除”!!! x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown """ 格式化""" pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """无条件被调用,通过实例访问属性 x.__getattribute__(‘name‘) <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown """ 内部调用 __new__方法或创建对象时传入参数使用 """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ 如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等 x.__hash__() <==> hash(x) """ pass def __hex__(self): # real signature unknown; restored from __doc__ """ 返回当前数的 十六进制 表示 x.__hex__() <==> hex(x) """ pass def __index__(self): # real signature unknown; restored from __doc__ """ 用于切片,对数字无意义 x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x, base=10): # known special case of int.__init__ """构造函数 int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100‘, base=0) 4 # (copied from class doc) """ pass def __int__(self): # real signature unknown; restored from __doc__ """ 转换为整数 x.__int__() <==> int(x) """ pass def __invert__(self): # real signature unknown; restored from __doc__ """按位求反 x.__invert__() <==> ~x """ pass def __long__(self): # real signature unknown; restored from __doc__ """转换为长整数 x.__long__() <==> long(x) """ pass def __lshift__(self, y): # real signature unknown; restored from __doc__ """ 左移,相对二进制的操作 x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ 取余 x.__mod__(y) <==> x%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ 返回两数相乘的积 x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ 返回一个数的负数,个人觉得和相反数没差 x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ 创建一个int类的新对象 T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ 判断一个数是不是0 x.__nonzero__() <==> x != 0 """ pass def __oct__(self): # real signature unknown; restored from __doc__ """ 返回该值的 八进制 表示 x.__oct__() <==> oct(x) """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ 位运算,或,针对二进制数 x.__or__(y) <==> x|y """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ 并没什么卵用,说是a.__pos__(),会返回一个+a,但是不管输入整数还是负数,返回值都是他本身,感觉歪果仁真有幽默感 x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ 幂,次方 x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """x.__radd__(y) <==> y+x """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ 转化为解释器可读取的形式 x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __str__(self): # real signature unknown; restored from __doc__ """ 转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式 x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ 返回两数相减的差 x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """返回两数相除的商,这里的除是精确的除法,不会省略小数点后的值 x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """返回数值被截取为整形的值,在整形中无意义 Truncating an Integral returns itself. """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ 按位异或 x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分母 = 1 """ """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 虚数,无意义 """ """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 分子 = 数字大小 """ """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """ 实数,无意义 """ """the real part of a complex number""" int Code
下面对于老师特别强调以后编程会用到的详细展开一下下:
(1)__abs__():取相反数
a=-12 b=10 result=a.__abs__() result1=b.__abs__() print(result) print(result1)
其输出为:12 10
(2)__add__():相加
a=-19 result=a.__add__(100) print(result)
在命令窗口是这样的:
(3)__floordiv__:不保留小数点后的小数除法
a=19 result=a.__floordiv__(6) print(result)
输出的值为3
(4)__init__():构造方法
创建数字的时候:
age=19或者 age=int(19)
这个时候会自动调用__init__()
(5)__divmod__:返回两个数相除的商和余数组成的元组(商,余数) 应用:显示网页数据中的分页
1 >>> a = 102 2 >>> b = 10 3 >>> a.__divmod__(b) 4 (10, 2)
二、长整型
其所有的功能如下:
class long(object): """ long(x=0) -> long long(x, base=10) -> long Convert a number or string to a long integer, or return 0L if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by ‘+‘ or ‘-‘ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100‘, base=0) 4L """ def bit_length(self): # real signature unknown; restored from __doc__ """ long.bit_length() -> int or long Number of bits necessary to represent self in binary. >>> bin(37L) ‘0b100101‘ >>> (37L).bit_length() """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ Returns self, the complex conjugate of any long. """ pass def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__(‘name‘) <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __hex__(self): # real signature unknown; restored from __doc__ """ x.__hex__() <==> hex(x) """ pass def __index__(self): # real signature unknown; restored from __doc__ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x=0): # real signature unknown; restored from __doc__ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __invert__(self): # real signature unknown; restored from __doc__ """ x.__invert__() <==> ~x """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): # real signature unknown; restored from __doc__ """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): # real signature unknown; restored from __doc__ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Returns size in memory, in bytes """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Truncating an Integral returns itself. """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number""" long
三、浮点型
如:3.14159
每个浮点型都具备如下功能:
class float(object): """ float(x) -> floating point number Convert a string or number to a floating point number, if possible. """ def as_integer_ratio(self): """ 获取改值的最简比 """ """ float.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs. >>> (10.0).as_integer_ratio() (10, 1) >>> (0.0).as_integer_ratio() (0, 1) >>> (-.25).as_integer_ratio() (-1, 4) """ pass def conjugate(self, *args, **kwargs): # real signature unknown """ Return self, the complex conjugate of any float. """ pass def fromhex(self, string): """ 将十六进制字符串转换成浮点型 """ """ float.fromhex(string) -> float Create a floating-point number from a hexadecimal string. >>> float.fromhex(‘0x1.ffffp10‘) 2047.984375 >>> float.fromhex(‘-0x1p-1074‘) -4.9406564584124654e-324 """ return 0.0 def hex(self): """ 返回当前值的 16 进制表示 """ """ float.hex() -> string Return a hexadecimal representation of a floating-point number. >>> (-0.1).hex() ‘-0x1.999999999999ap-4‘ >>> 3.14159.hex() ‘0x1.921f9f01b866ep+1‘ """ return "" def is_integer(self, *args, **kwargs): # real signature unknown """ Return True if the float is an integer. """ pass def __abs__(self): """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): """ x.__add__(y) <==> x+y """ pass def __coerce__(self, y): """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): """ x.__div__(y) <==> x/y """ pass def __eq__(self, y): """ x.__eq__(y) <==> x==y """ pass def __float__(self): """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, format_spec): """ float.__format__(format_spec) -> string Formats the float according to format_spec. """ return "" def __getattribute__(self, name): """ x.__getattribute__(‘name‘) <==> x.name """ pass def __getformat__(self, typestr): """ float.__getformat__(typestr) -> string You probably don‘t want to use this function. It exists mainly to be used in Python‘s test suite. typestr must be ‘double‘ or ‘float‘. This function returns whichever of ‘unknown‘, ‘IEEE, big-endian‘ or ‘IEEE, little-endian‘ best describes the format of floating point numbers used by the C type named by typestr. """ return "" def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, y): """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): """ x.__gt__(y) <==> x>y """ pass def __hash__(self): """ x.__hash__() <==> hash(x) """ pass def __init__(self, x): pass def __int__(self): """ x.__int__() <==> int(x) """ pass def __le__(self, y): """ x.__le__(y) <==> x<=y """ pass def __long__(self): """ x.__long__() <==> long(x) """ pass def __lt__(self, y): """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): """ x.__mul__(y) <==> x*y """ pass def __neg__(self): """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): """ x.__ne__(y) <==> x!=y """ pass def __nonzero__(self): """ x.__nonzero__() <==> x != 0 """ pass def __pos__(self): """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): """ x.__radd__(y) <==> y+x """ pass def __rdivmod__(self, y): """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): """ x.__rfloordiv__(y) <==> y//x """ pass def __rmod__(self, y): """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): """ x.__rmul__(y) <==> y*x """ pass def __rpow__(self, x, z=None): """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rsub__(self, y): """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): """ x.__rtruediv__(y) <==> y/x """ pass def __setformat__(self, typestr, fmt): """ float.__setformat__(typestr, fmt) -> None You probably don‘t want to use this function. It exists mainly to be used in Python‘s test suite. typestr must be ‘double‘ or ‘float‘. fmt must be one of ‘unknown‘, ‘IEEE, big-endian‘ or ‘IEEE, little-endian‘, and in addition can only be one of the latter two if it appears to match the underlying C reality. Override the automatic determination of C-level floating point type. This affects how floats are converted to and from binary strings. """ pass def __str__(self): """ x.__str__() <==> str(x) """ pass def __sub__(self, y): """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Return the Integral closest to x between 0 and x. """ pass imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default以上是关于Python学习第二天的主要内容,如果未能解决你的问题,请参考以下文章