Python Object Note 2

Notes on Python Types and Objects

Object-oriented relationships

The type-instance and supertype-subtype relationships:

  1. is a kind of (solid line): also known as specialization or inheritance, i.e., the subclass-superclass relationship
  2. is an instance of (dahsed line): also known as instantiation, i.e., when one (the instance) is a concrete example of what the other specifies(the type).

Relationship rules

  1. If A is a subclass of B, and B is a subclass of C, then A is a subclass of C.
  2. If X is an instance of A, and A is a subclass of B, then X is an instance of B.
  3. If B is an instance of M, and A is a subclass of B, then A is an instance of M.

Notes: the relationship of inheritance between classes and the relationship of instantiation between classes is deferent.

what is a Python object?

An object is an entity with the following characteristic properties:

  1. Identity
    • given two names we can say for sure if they refer to one and the same object, or not.
    • can be viewed as a pointer to the object's location in memory
  2. A value
    • which may include a bunch of attributes
    • we can reach other objects through object_name.attribute_name
    • if an object's value can be modified, the object is mutable, otherwise, immutable
    • an object that contains references to other objects is a container or collection
  3. A type
    • also known as the object's class
    • describes the internal representation of the object as well as the methods and operations it supports.
    • when an object of a particular type is created, that object is called an instance of that type
    • after an instance is created, its identity and type cannot be changed.
  4. One or more bases
    • a base is similar to a super-class or base-class in object-oriented lingo

tips:

Keep in mind that the types and bases of objects just other objects.

>>> two = 2
>>> type(two)
<class 'int'>
>>> type(type(two))
<class 'type'>
>>> type(two).__bases__
(<class 'object'>)
>>> type(type(two).__bases__[0])
<class 'type'>

Chicken and Egg

type and object are primitive objects in Python, they cannot stand on their own since they are defined in terms of each other.

>>> isinstance(object, object)
True
>>> isinstance(type, object)
True
>>> isinstance(object, type)
True

thus:

  1. <class 'type'> is a subclass of <class 'object'>, instances of <class 'type'> are instances of <class 'object'>as well.
  2. <class 'type'> is an instance of itself and <class 'object'>
  3. <class 'object'> is an instane of itself and <class 'type'>

Everything is an object in Python

  • you can store them in variables
  • you can pass them as parameters to functions
  • you can return them as the result of functions
  • you can construct them at runtime
>>> two = 2
>>> dir(two) == dir(2)
True
>>> two.__class__
<class 'int'>
>>> 2.__class__
SyntaxError: invalid syntax
>>> (2).__class__
<class 'int>'

Functions as objects

  • when you use the keyword def, Python creates a function object.
  • functions can be passed around as arguments to other functions.
  • these functions that take other functions as arguments are called higher order functions.

Classes as objects

  • when you use the keyword class, Python executes it and creates an object.
  • this object (the class) is itself capable of creating objects(the instances), and is always the same for all instances of a given type.
  • since classes are objects, they must be generated by something this is metaclasses.
  • since metaclasses are objects, they must be generated by something, this is again metaclasses.

Therefore: Objects are instances of classes, classes are instances of metaclasses and metaclasses are instances of themselves.

Metaclasses as objects

  • metaclass are the "staff" that creates classes.
    • MyClass = MetaClass()
    • MyObject = MyClass()

Reference Counting and Garbage Collection

  1. The name of an object is not really part of the object. The name exists outside of the object in a namespace or as an attribute of another object.
  2. All objects are reference-counted, an object's reference count is increased whenever it's assigned to a new name or placed in container(list, tuple, dictionary)
  3. an object's refenence count is decreased by the del statement or whenever a reference goes out of scope (or is reassigned)
  4. When an object's reference count reaches zero, it is garbage-collected.
    • the intepreter periodically executes a cycle detector that searches for cycles of inaccessible objects and delete them.
a = 37  # creates an object with value 37
b = a   Increase reference count on 37
c = []
c.append(b)  # Increase reference count on 37

del a  # Decrease reference count on 37
b = 42  # Decrease reference count on 37
c[0] = 2  # Decrease reference count on 37

References and Copies

For mutable objects such as lists and dictionaries, when perfom assignments operations such as a = b, a chage made to oneof the variables is reflected in the other.

a = [1, 2, 3, 4]
b = a  # b is a reference to a
b is a  # True
b[2] = -100 # change an elem in b
a  # [1, 2, -100, 4], also changed.

To avoid this, we have to create a copy of an object rather than a new reference. Two types of copy operations are applied to container objects:

  1. a shallow copy

Creates a new object but populates it with references to the items contained in the original object

a = [1, 2, [3, 4]]
b = list(a)  # Create a shallow copy of a
b is a  # False
b.append(100)  # append element to b
a  # [1, 2, [3, 4]], a is unchanged

b[2][0] = -100  # modify an element inside b
a  # [1, 2, [-100, 4]], a is changed

a and b are separate list objects, but the elements they contain are shared, this is shallow copy.

  1. a deep copy
    • creates a new objects and recursively copies all the objects it contains.
    • in the standard library copy.deepcopy() function can be used.

what are type objects?

  • They are used to represent abstract data types in programs.
  • They can be subclassed, you can create a new object that is somewhat similar to existing type objects.
  • They can be instantiated, you can create a new object that is an instance of the existing type objec.
  • the type function lets you know what type an object is
  • type can also create classes on the fly. type can take the description of a class as parameters, and return a class as type(name, bases, dct).
    • name is a string giving the name of the class to be constructed.
    • bases is a tuple giving the parent classes of the class to be constructed.
    • dct is a dictionary of the attributes and methods of the class to be constructed.
  • type is the metaclass Python uses to create(instantiate) all classes and metaclasses, including type itself.
  • type is actually its own metaclass. This is not something you could reproduce in pure Python, and is done by cheating a little bit at the implementation level.

Racap:

  1. Class is Type is Class
  2. If an object is an instance of `<class 'type'>, then it is a type. Otherwise, it is not a type

More Built-in Types

The two primitives Type and Object come with a whole gang of buddies:
builtin types

what is object class?

  • object is the class that all classes inherit from.
  • all classes including object are subclasses of themselves.
  • all classes including object are subclasses of object. object.__bases__ is an empty tuple.
  • all classes except object will have object in bases in a class in their inheritance hierarchy.

Kinds of objects in python

  • there are two kinds of objects in Python
    • Type objects that can create instances, can be subclassed. e.g. type, object, int, str, list
    • Non-type objects that cannot create instances, cannot be subclassed. e.g. 1, "hello", [1, 2, 3].
  • type and object are two primitive objects of the system.
  • object_name.__class__ exists for every object and points the type of the object.
  • object_name.__bases__ exists for every type object and points the superclass of the object. It is empty only for object.

The built-in objects are built into Python. New objects cannot pop out of thin air, they have to be built using existing objects.

New Objects by Subcalssing

Use the class statement and specify the bases(and, optionally, the type) of the new object. This always creates a type object.

New Objects by Instantiating

Use the call operator on the type objects to create a new object. This may create a type object or a non-type-object.

obj = object()
cobj = C()
mylist = [1, 2, 3]
  1. The call operator () creates a new object by instantiating an existing object. The existing object must be a type. Depending on the type, the call operator might accept arguments.
  2. Addition, Python syntax can create some non-type objects.

user builtin Objects

Recap

  1. all classes and metaclasses including object are subclasses of object.
  2. all classes and metaclasses including type are instances of type.
  3. all objects including object are instances of object.
posted @ 2017-03-21 15:22  Cunde  阅读(270)  评论(0)    收藏  举报