Object Identity and
01 Reference Counting
• Object Identity and Type
• Reference Counting and Garbage Collection
Exercise
Q. Write a python program to reverse a string.
Note If the input string is xyz5678,
the expected output will be 8765zyx.
s= input("Enter string:")
print (s[::-1])
2
18
Object Identity and Type
• Every piece of data stored in a program is an object.
Identity
Object Type
Value
3
18
Object Identity and Type
• When an object of a particular type is created, that
object is sometimes called an instance of that type.
• After an instance is created, its identity and
type cannot be changed.
4
18
Object Identity and Type
Object’s
Value
Cannot
Can be
be
modified
modified
mutable immutable
5
18
Object Identity and Type
id()
• The built-in function returns the identity
of an object as an integer.
• This integer usually corresponds to the
object’s location in memory.
6
18
Object Identity and Type
is operator
type operator
• compares the
• returns the type of
identity of two
an object
objects
7
18
Object Identity and Type
# Compare two objects
def compare(a,b):
if a is b:
# a and b are the same object
statements
if a == b:
#a and b have the same value
statements
if type(a) is type(b):
# a and b have the same type
8 statements
18
Object Identity and Type
• The type of an object is itself an object known as
the object’s class.
• This object is uniquely defined and is always the
same for all instances of a given type.
• The type can be compared using the is operator.
• All type objects are assigned names that can be
used to perform type checking.
9
18
Object Identity and Type
• Most of these names are built-ins,
such as list, dict and file.
• Example:
if type(s) is list:
s.append(item)
if type(d) is dict:
d.update(t)
10
18
Object Identity and Type
• A better way to check types is to use the
built-in isinstance(object, type) function.
if isinstance(s,list):
s.append(item)
if isinstance(d,dict):
d.update(t)
11
18
Reference Counting and Garbage Collection
• All objects are reference-counted.
• An object’s reference count is increased whenever
it’s assigned to a new name or placed in a
container such as a list, tuple, or dictionary.
12
18
Reference Counting and Garbage Collection
a = 37 # Creates an object with value 37
b=a # Increases reference count on 37
c = []
c.append(b) # Increases reference count on 37
13
18
Reference Counting and Garbage Collection
• An object’s reference count is decreased by the
del statement or whenever a reference goes out
of scope (or is reassigned).
del a # Decrease reference count of 37
b = 42 # Decrease reference count of 37
c[0] = 2.0 # Decrease reference count of 37
14
18
Reference Counting and Garbage Collection
sys.getrefcount()
• The current reference count of an
object
>>> a = 37
>>> import sys
>>> sys.getrefcount(a)
15
18
Reference Counting and Garbage Collection
• When an object’s reference count reaches zero,
it is garbage-collected.
• In some cases a circular dependency may exist
among a collection of objects that are no longer in
use.
16
18
Reference Counting and Garbage Collection
• Each object contains a reference to the other,
the reference count doesn’t drop to zero and
the objects remain allocated.
• To address this problem, the interpreter
periodically executes a cycle detector that
searches for cycles of inaccessible objects
and deletes them.
17
18
Reference Counting and Garbage Collection
• The cycle-detection algorithm runs
periodically as the interpreter allocates more
and more memory during execution.
18
18
02 References and
Copies
Data and
03 Program Structure
• Build in Types for Representing Data
• Build in Types for Representing Program Structure
Built-in Types for Representing Data
type (None) The null object None
int Integer
long Arbitrary-precision integer
float Floating point
complex Complex number
2 bool Boolean (True or False)
17
Built-in Types for Representing Data
str Character string
unicode Unicode character string
( Python 2 only)
list List
tuple Tuple
xrange A range of integers created by xrange ()
3
17 (In Python 3, it is called range)
Built-in Types for Representing Data
dict Dictionary
set Mutable set
frozenset Immutable set
4
17
Built-in Types for Representing
Program Structure
Type
Type Name Description
Category
Callable types.BuiltinFunctionType Built-in function or method
type Type of built-in types and classes
object Ancestor of all types and classes
types.FunctionType User-defined function
types.MethodType Class method
5
17
Built-in Types for Representing
Program Structure
Type
Type Name Description
Category
Modules Types.ModuleType Module
Ancestor of all types
Classes object
and classes
Types of built-in types
Types type
and classes
6
17
Callable Types
• Callable types represent objects that support the
function call operation.
• There are several flavors of objects with this
property, including user-defined functions, built-in
functions, instance methods, and classes.
7
17
User- defined Functions
• User-defined functions are callable objects
created at the module level by using the
def statement or with the lambda operator.
def foo(x,y):
return x + y
(or)
bar = lambda x,y: x + y
8
17
Methods
• Methods are functions that are defined inside
a class definition.
class
Method instance
static
9
17
Methods
instance method
• Instance method is a method that operates on an
instance belonging to a given class.
• The instance is passed to the method as the first
argument, which is called self by convention.
def instance_method(self,arg):
statements
10
17
Methods
class method
• A class method operates on the class itself as an
object.
• The class object is passed to a class method in
the first argument, cls.
@classmethod
def class_method(cls,arg):
statements
11
17
Methods
static method
• A static method is a just a function that happens
to be packaged inside a class.
• It does not receive an instance or a class object
as a first argument.
@staticmethod
def static_method(arg):
statements
12
17
Classes and Instances as Callables
• Class objects and instances also operate as
callable objects.
• A class object is created by the class
statement and is called as a function in order
to create new instances.
13
17
Classes and Instances as Callables
• In this case, the arguments to the function are
passed to the __init__() method of the class in
order to initialize the newly created instance.
• An instance can emulate a function
if it defines a special method, __call__().
14
17
Classes and Instances as Callables
• If this method is defined for an instance, x,
then x(args) invokes the method
x.__call__(args).
15
17
Classes, Types, and Instances
• When you define a class, the class definition
normally produces an object of type.
>>> class Foo(object):
pass
>>> type(Foo)
<type 'type'> # python 2
<class ‘type’>
16
17
Classes, Types, and Instances
• When an object instance is created, the type
of the instance is the class that defined it.
>>> f = Foo()
>>> type(f)
<class '_ _main_ _.Foo'>
17
17