def main(): print 'Ran the main method' if __name__ == '__main__': main() class PositiveInteger(int): def __new__(cls, number): if number < 0: raise ValueError('The number has to be positive integer') else: return int.__new__(cls, number) def __init__(self, number): self.number = number def get_number(self): return self.number p = PositiveInteger(1) p.get_number() PositiveInteger(-2) with open('numbers.txt') as numbers: list_of_numbers = numbers.read() print list_of_numbers.split() print numbers print numbers class Redis(object): def __init__(self, rdb): self.connection = CreateConnection(rdb) def __enter__(self): return self.connection def __exit__(self): self.connection.close() with Redis('redis://localhost:6379') as redis: # do things with new redis connection. redis.set('neck', 'beard') class Person(object): def __init__(self, name='', age=10): self.name = name self.age = age def __repr__(self): return "Person(name=%r, age=%r)" % (self.name, self.age) def __str__(self): return 'A person name %s at age %d' % (self.name, self.age) p = Person(name='Mahdi', age=50) print str(p) print repr(p) p2 = Person(name='Mahdi', age=50) print p2 from functools import total_ordering @total_ordering class Name(object): def __init__(self, name): self.name = name def __eq__(self, other): if isinstance(other, Name): return len(self.name) == len(other.name) return False def __lt__(self, other): if isinstance(other, Name): return len(self.name) < len(other.name) return False mahdi = Name('Mahdi') mikey = Name('Mikey') kelsey = Name('Kelsey') print mahdi == mikey print mahdi <= mikey print kelsey > mahdi class Friend(object): def __init__(self, name, nickname): self.name = name self.nickname = nickname def __getattr__(self, name): raise AttributeError('The attribute you asked for %s for does not exist, clean it up sloppy'% name) def __setattr__(self, name, value): if value == "Mahdi the Potty" and name == 'nickname': raise ValueError("No one calls me Mahdi the Potty") else: self.__dict__[name] = value f = Friend('Mahdi', 'Mahdi the Bahdi') # f.first_name f.nickname = "Mahdi the Ladidai" class First(object): pass class Fifth(object): pass class Second(First): pass class Third(Fifth): pass class Fourth(Third, Second): def __init__(self): pass print Fourth.__mro__ class Point(object): def __init__(self, x, y): self.x = x self.y = y class Point1(object): __slots__ = ('x', 'y') def __init__(self, x, y): self.x = x self.y = y p = Point(5, 6) p1 = Point1(5, 6) p.z = 9 print p.z #p1.z = 8 p1.y = 10 p1.x = 9 print p1.y print p1.x p.__dict__ #p1.__dict__ #p1.x = 9 #p1.__dict__ p1.z = 5