self.[ATTR] are defined only when an object of the class is instantiated
class SimpleClass():
x = 1 #Static. exists without instatiation
#This method is executed only when class is instantiated
def __init__(self):
print(type(self))
self.y = 2
Get the class WITHOUT instantiating. Note that there is no paranthesis
#Get the class WITHOUT instantiating. Note that there is no paranthesis
x = SimpleClass
#__init__ is not run
x
#This attribute is defined eventhough we have not instantiated. These are static attributes
x.x
#y is not defined, as we have not yet instantiated
x.y
Instantiate the class
#Instantiate the class
y = SimpleClass()
#runs __init__
y.x
#Now y is defined
y.y
.dict
#Shows only instance attributes
y.__dict__
#Shows class attributes
x.__dict__
The super class constructor is not called by default, when the child class is instantiated. The super class constructor should be explicitly called to be executed
class Extend(SimpleClass):
def __init__(self):
#Does not run the __init__ of super class
self.z = 3
z = Extend()
#The init of SimpleClass is not run. So y is not defined
z.__dict__
#But x is still inherited
z.x
class Extend2(SimpleClass):
def __init__(self):
#Super class constructor is explicitly clalled
super().__init__()
self.z = 3
w = Extend2()
#Now the super class __init__ is run
w.__dict__
def f(x:int,s:str) -> float:
print(s)
return float(x)
Can be used to check the return type and argument types expected
f
f.__annotations__
f(2,"Aravind")
However, it does not check if the correct types are passed. For this, you can create a custom assertion with annotation
f(1,2)
To specify types that are structured, use typing module
from typing import Tuple
def g() -> Tuple[int,str,float]:
return (1,"hi",3.0)
g()
g.__annotations__
Can also pass a custom struct
fd = {'type':int, 'units':'Joules','help':"bla bla bla"}
def h() -> fd:
return 2
h
Useful when you have a large dataset which does not fit in memory when used as list
Used to build generator functions
def generator():
a = [1,2,3,4,5]
# returns 1 when generator() is called first time
# returns 2 when generator() is called second time
# ....
for i in a:
print("called!")
yield i
for i in generator():
print(i)