Python Object Note 1
- Python Objects
- Built-in Types
- standard Type Operators
- Value Comparison
- Object Identity Comparison
- Boolean
- Standard Type Built-in Functions
- Categorizing the Standard Types
- Miscellaneous Types
- Unsupported Types
2. Python Objects
Python use the object model abstraction for data storage. Any construct that contains any type of value is an object.
All Python objects have the following three characteristics: an identity, a type, and a value.
All three are assigned on object creation, and the identity is read-only. For new-style types and classes, it may possible to change the type of an object. Whether an object's value can be changed is known as an object's mutability.
Python supports a set of basic data types.
2.1 Object Attributes
The most familiar attributes are functions and methods, some Python types also have data attributes associated with them.
Objects with data attributes include: classes, class instances, modules, complex numbers, and files.
3. Standard Types
- Integer
- Boolean
- Long integer
- Floating point real number
- Complex number
- String
- List
- Tuple
- Dictionary
These types represent the primitive data types that Python provides.
4. Other Built-in Types
- Type
- Null object (None)
- File
- Set/Frozenset
- Function/Method
- Module
- Class
4.1 Type object and the type Type Object
An object's set of inherent behaviors and characteristics (such as supported operators and built-in methods) must be defined somewhere, an object's type is a logical place for this information.
You can find out the type of an object by calling the type() BIF with that object.
>>> type(42)
<type 'int'>
>>> type(type(42))
<type 'type'>
The type of all type objects is type. The type type object is also the mother of all types and is the default metaclass for all standard Python classes.
4.2 None, Python's Null Object
- The type of None is NoneType
- It has only one value, None
- It does not have any operators or BIFs
- None has no attributes
- It always evaluates to having a Boolean
False
value
Core Note: Boolean values
All standard type objects can be tested for truth value and compared to objects of the same type.
The following are defined as having false
values in Python:
- None
- False
- Any numeric zero:
- 0 (integer)
- 0.0 (float)
- 0L (long integer)
- 0.0+0.0j (complex)
- "" (empty string)
- [] (empty list)
- () (empty tuple)
- {} (empty dict)
- User-created class instances have a
false
value when their nonzero(__nonzero__()
) or length (__len__()
) special methods return a zero value
5. Internal Types
- code
- Frame
- Traceback
- Slice
- Elipsis
- Xrange
- exceptions
Refer to the source code or Python internal and online documentation for more information.
5.1 Code Objects
- executable pieces of Python source
- are byte-complied, usually as return values from calling the
compile()
BIF - are appropriate for execution by either
exec
or by theeval()
BIF
Code objects themselves do not contain any information regarding their execution environment, but they are at the heart of every user-defined function:
- The actual byte-complied code as a code object is one atribute belonging to a function
- a function's attributes also consist of the administrative support including its name, doc-string, default arguments, and global namespace.
5.2 Frame Objects
- execution stack frames in Python
- contain all the information the interpreter needs to know during a runtime execution environ
- each function call results in a new frame object
- for each frame object, a C stack frame is created as well
- can be accessed in a traceback object
5.3 Traceback Objects
- a data item that holds the stack trace info for an exception
- is created when an exception occurs
- if a handler is provided for an exception, this handler is given access to the traceback object.
5.4 Slice Objects
- Slice objects are created using the Python extended slice syntax
- can also be generated by the
slice()
BIF
5.5 Ellipsis Objects
- represent the actual ellipses int the slice syntax(
...
) - ellipsis have a single name,
Ellipsis
- have a Boolean
True
value at all times
5.6 XRange Objects
- created by the BIF
xrange()
- used when memory is limited and when
range()
generates an unususlly large data set
Notes: take a look at the types
module in the SPL
6. Standard Type Operators
6.1 Object Value Comprison
- used to determine equality of two data values between members of the same type
- yield Boolean
True
orFalse
values - the list of comparison operators are supported for all built-in types:
<
>
<=
>=
==
!=
numeric types are compared according to numeric value in sign and magnitude, strings will compare lexicographically.
multiple comparisons can be made on the same line, evaluated in left-to-right order.
6.2 Object Identity Comparison
- Objects can be assigned to other variables by reference
- Each objects has associated with it a counter that tracks the total number of references that exist to that object
- the
is
andis not
operators are used to test if a pair of variables refer to the same object
Core Note: Interning
Python caches only simple integers to be more efficient.
6.3 Boolean
- not, and, or used to link expressions
- one level below all the comparison operators
- yield Boolean
True
orFalse
values
7. Standard Type Built-in Functions
some BIFs can be applied to all the basic object types:
- cmp(obj1, obj2)
- returns integer i < 0 if obj1 < obj2
- returns integer i > 0 if obj1 > obj2
- returns integer i == 0 if obj1 == obj2
- repr(obj)
- return evaluatable string representation of obj
- str(obj)
- return printable string representation of obj
- type(obj)
- return type object of obj
7.1 type()
earlier than Python 2.2, type() is a BIF. Since that release, it has become a "factory function"
>>> type(4)
<type 'int'>
In some scenarios where there is no easy way to "display" an object, Python "pretty-prints" a string representation of the object. The format is usually of the form: <object_something_or_another>
7.2 cmp()
The comparison used is the one that applies for that type of object, whether it be a standard type or a user-created class. If the latter, cmp()
will call the class's special __cmp__()
method.
7.3 str() and repr()
Used to re-create an object through evaluation or obtain a human-readable view of the contents of objects, data values, object types, etc.
- repr() will deliver the "official" string representation of an object that can be evaluated as a valid Python expression (using the eval() BIF).
- str() will deliver a "printable" string representation of an object, which may not necessarily be accessed by
eval()
Caveat: not all return values from repr()
can be evaluated by eval()
7.4 type() and isinstance()
Used to help determine the type of an object.
Using isinstance() along with type objects is the accepted style of usage when introspecting objects' types.
7.5 Python Type Operator and BIF Summary
- Built-in functions
cmp
repr
str
type
- Value comparisons
<
>
<=
>=
==
!=
- Object comparisons
is
is not
- Boolean operators
not
and
or
8. Type Factory Functions
BIFs like int(), type(), list(), etc. are factory functions, when you call one, you are actually instantiating an instance of that type, like a factory producing a good.
int(), long(), float(), complex()
str(), unicode(), basestring()
list(), tuple()
type()
dict()
bool()
set(), frozenset()
object()
classmethod()
staticmethod()
super()
property()
file()
9. Categorizing the Standard Types
the standard types are something like Python's "basic built-in data object primitive types"
how each type works:
- how they function
- how their data values are accessed
- whether can be updated
- what kind of storage provided
9.1 Storage Model
how many objects can be stored in an object of this type:
- atomic or scalar storage, holds a single literal object
- container storage, holds multiple objects (and different types)
Scalar/atom --> Numbers, strings
Container --> Lists, tuples, dict
9.2 Update Model
can objects be changed, or can their values be updated?
- Mutable objects
- immutable objects
Mutable --> Lists, dictionaries
Immutable --> Numbers, strings, tuples
9.3 Access Model
how do we access the values of our stored data?
- Direct
- single-element, non-container types
- Numbers
- Sequence
- elements are sequentially accessible via index values startin at 0
- strings, lists, and tuples.
- Mapping
- elements are unordered and accessed with a key
- a set of hashed key-value pairs
Recap:
Numbers | scalar | immutable | direct |
---|---|---|---|
Strings | scalar | immutable | sequence |
Lists | container | mutable | sequence |
Tuples | container | immutable | sequence |
dict | container | mutable | mapping |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步