In [1]:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
In [6]:
dir(m)
Out[6]:
In [5]:
m.__doc__
Out[5]:
In [2]:
m=MyClass()
In [3]:
m.i
Out[3]:
In [4]:
m.f()
Out[4]:
In [9]:
class AnotherClass:
def __init__(self,i=1234):
self.i=i
In [10]:
a=AnotherClass()
a.i
Out[10]:
In [11]:
a=AnotherClass(456)
a.i
Out[11]:
In [26]:
class Rect:
def __init__(self,x=0,y=0,w=0,h=0):
self.x=x
self.y=y
self.w=w
self.h=h
In [28]:
r=Rect(1)
In [27]:
r=Rect(7,8,9,10)
In [135]:
class Rect(object):
def __init__(self,x=0,y=0,w=0,h=0):
self.x=x
self.y=y
self.w=w
self.h=h
def __str__(self):
return "x: %s, y: %s, w: %s, h: %s"%(self.x, self.y, self.w, self.h)
In [136]:
r=Rect(7,8,9,10)
In [137]:
print r
In [138]:
class Square(Rect):
def __init__(self,x=0,y=0,w=0):
super(Square,self).__init__(x,y,w,w)
def __str__(self):
return super(Square,self).__str__()
In [140]:
s=Square(2,3,4)
print s
In [127]:
r.__str__()
Out[127]:
In [54]:
x.i
Out[54]:
In [55]:
y.i
Out[55]:
In [56]:
z=x+y
In [57]:
type(z)
Out[57]:
In [59]:
Out[59]:
In [60]:
x="Hello"
In [61]:
y="World"
In [63]:
x+" "+y
Out[63]:
In [104]:
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
In [107]:
x=[1,2,3,4,5,6]
for i in reverse(x):
print i
In [300]:
class Node(object):
L=None
R=None
def __init__(self, x=[],depth=0, side="T"):
self.depth=depth
self.side=side
self.x=x
if 1<len(x):
index=len(x)/2
self.theta=x[index]
self.L=Node(x[:index], depth+1, side="L")
self.R=Node(x[index:], depth+1, side="R")
def show(self):
if self is not None:
print self
if self.L:
self.L.show()
if self.R:
self.R.show()
def __str__(self):
if len(self.x)==1:
return "%s%s, x: %s"%(" "*self.depth, self.side, self.x)
else:
return "%s%s, theta: %s"%(" "*self.depth, self.side, self.theta)
In [301]:
n=Node([1,2,3,4,5,6,7,8,9,10])
In [302]:
n.show()
In [320]:
class Book(object):
def __init__(self,name="untitled", pages=0):
self.name=name
self.pages=pages
def __str__(self):
return "name: %s, pages: %s"%(self.name, self.pages)
def __repr__(self):
return "name: %s, pages: %s"%(self.name, self.pages)
def __add__(self, other):
return Book(name=self.name+"&"+other.name, pages=self.pages+other.pages)
In [321]:
math=Book("Mathematics",306)
phy=Book("Physics",210)
In [322]:
math+phy
Out[322]:
def __lt__(self, other):
return self.pages < other.pages
def ___le__(self, other):
return self.pages <= other.pages
def __eq__(self, other):
return self.pages == other.pages
def __ne__(self, other):
return self.pages != other.pages
def __gt__(self, other):
return self.pages > other.pages
def __ge__(self, other):
return self.pages >= other.pages
ref: https://docs.python.org/3/reference/datamodel.html#special-method-names
In [ ]: