Objects in Python

From Sustainability Methods

THIS ARTICLE IS STILL IN EDITING MODE

Introduction- What Objects are there?

An object is simply a collection of data and methods. This data can be variables and functions. For example, if x=1, x is an object.

Variables and Data Types

Variables are just like a container for storing data values. For example, if y=2. It means 'y' is a variable assigned with an integer value of 2.

Variables Example
X x=5
Y y=2
Z z=x+y

Data Types are simple variable definitions. Data types in Python are; primitive, abstract, and composite. [Explanation needed? Does this refer to the respective examples above?]

Different Data Types in Python

Data Types Example
Primitive integer, float, strings, boolean
Abstract set, stack, tree, vector, map, queue
Composite list[], tuple [], dict[]

Save, load, and declare Objects

You can create a Python object by assigning a value to a variable. In subsequent lines of code, you can use that variable to access the designated value. For example, in the following code, we assign the value 1 to variables x and y and then use the variables to create a new object z:

x = 1 
y = 1
z = x + y
print(z)
>>> Output: 2

Note that you will overwrite the value saved in an object if you assign something new to it. For example, you may re-assign another value to x in the example above. Note how what is stored in x changes:

x = 1 
y = 1
z = x + y
print(x)
>>> Output: 1

x = "gryffindor"
print(x)
>>> Output: gryffindor

Object Types

In contrast to statically typed programming languages like C++ and Java, Python is dynamically typed, which means that you do not need to explicitly declare the data type. So, in the example above, Python automatically identifies that variable x contains the integer 1. The following table provides an overview of some of the most important Python objects and how to implement them in code.

Object Type Description Implementation
String sequence of character s = "slytherin"
Integer whole number i = 1
Float decimal number f = 1.0
Boolean True or False b = True
List mutable*, ordered**, collection of values l = [a, b]
Tuple immutable, ordered collection of values t = (a, b)
Set unordered collection of unique values z = {a, b}
Dictionary mutable, ordered mapping of unique keys to values d = {"key1" : "value1", "key2": "value2"}

Mutable means that an object can be changed after it has been created. For example, you can add or delete elements to an already existing list.

Ordered means that the individual elements of an object have fixed indices that you can use to reference them. For example, `l[0]` returns the first element of the list l.

While Python generally identifies the data type of an object for you, you may find yourself wanting to change the data type of an object. There are multiple built-in functions that return a new object representing the converted value. For example, the following code allows you to perform addition on a string c and an integer d, which would otherwise result in an error:

a = 1
b = "1" 
c = a + b
>>> Output: TypeError

b = int(b)
c = a + b
print(c)
>>> Output: 2

Some useful conversions, besides `int()`, include `str()`, `tuple()`, and `list()`. The following code shows some examples of how to use them:

m = 1
m_string = str(1)
print(m_string, type(m_string))
>>> Output: 1 <class 'str'>

n = "hufflepuff"
n_tuple = tuple(n)
print(n_tuple, type(n_tuple))
>>> Output: ('h', 'u', 'f', 'f', 'l', 'e', 'p', 'u', 'f', 'f') <class 'tuple'>

n_list = list(n)
print(n_list, type(n_list))
>>> Output: ['h', 'u', 'f', 'f', 'l', 'e', 'p', 'u', 'f', 'f'] <class 'list'>

n_set = set(n)
print(n_set, type(n_set)
>>> Output: {'e', 'h', 'p', 'u', 'f', 'l'} <class 'set'>

Generally, conversion functions share the following same syntax:

<required_datatype>(object)

The explicit type conversion of objects described above can be distinguished from implicit type conversion, where Python changes the type of an object automatically. For example, the result of adding up an integer and a float will be a float.

If you are ever unsure what type of object you are dealing with, you can pass it into the `type()` function as follows:

l = [1, 2, 3]
l_type = type(l)
print(l_type)

>>> Output: <class 'list'>

Conversion and type() function

Function Function What it does
int(x) float, str (like '25') Convert x to a int, parse a string as an int

In case of float, cut off the decimals. For rounding float to int, use round(x)

float(x) int, str (like '10.4') Convert x to a float, parse a string as a float
str(x) any type Get the string representation of x
list(x) any iterable type (another list, set, map, zip, dict (keys only)) Convert x to a list
dict(key=value) key-value pairs as named arguments Create a dictionary with arguments as key-value pairs

Concatenating/Adding two Objects

Object / Data Type number string boolean list
number number 1 + 2.5 = 3.5 unsupported number1 + True = 2 unsupported
string unsupported string "Hello " + "world!" = "Hello world!" unsupported unsupported
boolean number False + 2 = 2 unsupported number True + False = 1 unsupported
list unsupported unsupported unsupported list [1,2,3] + ["one","two","three"] = [1,2,3,"one","two","three"]

Multiplying two Objects

Object / Data Type number string boolean list
number number 2 * 2.5 = 5 string 2 * "Hello" = "HelloHello" number 5 * False = 0 list2 * [1,2,3] = [1,2,3,1,2,3]
string string "200" * 2 = "200200" string
“Hello” * False = “”`
- -
boolean number True * 2 = 2 string True * "Hello" = "Hallo" number True * True = 1 list False * [1,2,3] = []
list list ["one","two","three"] * 2 = ["one","two","three","one","two","three"] - list True * [1,2,3] = [1,2,3] -


The author of this entry is XX. Edited by Milan Maushart