-2

我来自 Java 编程,不熟悉 Python。我是否应该将整数、浮点数和字符串文字也视为 python 编程的对象?

例如:2, 4.3,'stackoveflow'

4

4 回答 4

3

Everything in python is an object. Even functions and plain numbers/booleans.

Objects are Python’s abstraction for data. All data in a Python program is represented by objects

This has quite some advantages, for example, you can easily subclass a type such as str or unicode if you need a custom type with the default behaviour but additional features (often done in template engines to mark strings as HTML-safe).
Another more common thing is the join() method on strings. While most languages have such a methods on arrays, Python has it as a string method which is used like this, allowing you to pass any iterable/sequence to it: ', '.join(some_iterable)

于 2012-05-17T09:02:05.427 回答
1

Yes, every value is an object in Python. For example:

>>> dir(3)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> (3).__str__()
'3'
于 2012-05-17T09:02:09.267 回答
1

在 Python 中,每个值都是一个对象42, "stackoverflow", 和(1,)都是对象并且有一个类型

>>> (42).bit_length() # parentheses necessary for syntactic reasons
6
>>> "stackoverflow".upper()
'STACKOVERFLOW'
>>> type((1,))
<type 'tuple'>
于 2012-05-17T09:03:41.577 回答
1

是的。事实上,这样做是一些常见习语的核心——尤其是字符串格式:

>>> "Hello {}".format("name")
'Hello name'

并加入一个序列的项目:

>>> a = ['one', 'two', 'three']
>>> ' + '.join(a)
'one + two + three'

这两者都依赖于作为对象的字符串文字,因此能够在它们上调用方法。

于 2012-05-17T09:04:16.353 回答