3. Variables, Objects, and Classes - JulTob/Python GitHub Wiki
🐍 Variables and Objects
Variables, or Data Objects, are named memory spaces
holding values.
a = 0
b = 1
type(a) # int
a, b = b, a # Swap
print (a)
print (a,b)
x, y ,z = "Axis-x", "Axis-y", "Axis-z"
x = y = z = "Axis"
del a # Deletes variables
speed_of_light = 299792458
billionth = 1.0 / 100000000
print(speed_of_light)
nanostick_cm= speed_of_light * billionth * 100
cycles_per_second = 2700000000 #2.7GHz
distance_light_in_cycle= speed_of_light / cycles_per_second
print(distance_light_in_cycle)
message = 'And now for something completely different'
🦕 Types
A data type is a set of values and a set of operations defined on those values.
type Set of Operators sample literals
int Integers + - * // % ** 99 12 1000
float Floating Point Numbers + - * / ** 3.14 2.5 1000.00
bool Boolean Values and or not True False
str Sequences of characters + 'AB0' "Hello"
🐉 Class
Self-made new types of data. They can contain variables (Properties) and processes (methods).
In Python, all inner values (properties) and processes (methods) are public. Should-be-Restricted elements start with underscore [_]
class class_name:
#Constructor
def __init__(self, parameters):
#Code
#Properties
#Methods
fname.__doc__
>>> doc string
class triangle:
def __init__(self, base, height):
self.area = area(base,height)
def area(self, base, height):
a= 0.5 * base * hight
return a
def get_area(self, base, height):
return self.area
class dummy:
variable = "blah"
def function(self):
print("A message in the class")
🦖 Properties & Methods
"Properties" are objects (variables) inside the object. They exist when initialized. Methods are actions subjected to an object.
class MyClass:
x = 5
_x = 4 # "private"
def Put(my):
print(my.x)
#---------
obj = MyClass() # constructor
print(obj.x)
print(obj._x) # it does work
obj.Put()
del obj.x
del obj
🐢 Constructor
the constructor init (with two underlines each side)
class User:
def __init__(self, name, ID, access_level):
self.name = name
self.ID = ID
self.access_level = access_level
#Method
def Present(self):
print(self.name + " reporting for duty.")
User_1 = User("Jane Doe", "007", "Agent")
User_1.Present()
🐊 Self referencing
The first parameter of a method is the alias to the object itself. The User class can be rewritten as:
class User:
def __init__(stupid, name, ID, access_level):
stupid.name = name
stupid.ID = ID
stupid.access_level = access_level
#Method
def Present(dumb):
print(dumb.name + " reporting for duty.")
User_1 = User("Jane Doe", "007", "Agent")
User_1.Present()
🦎 Inheritance
class Shape:
def __init__(shape, Sides, Area):
shape.Sides = Sides
shape.Area= Area
class Square(Shape):
def __init__(square, l):
Shape.__init__( square, 4, l*l)
sq = Square(12)
print (sq.Sides)
print (sq.Area)
🐕🦺 IS
The keyword is
simply checks whether both variables refer to the same object in memory.
y = x = 3
print(x is y)
# True