Skip to content

Instantly share code, notes, and snippets.

@simplytunde
Last active August 29, 2015 14:12
Show Gist options
  • Save simplytunde/a17cd44c43c913d2c4d7 to your computer and use it in GitHub Desktop.
Save simplytunde/a17cd44c43c913d2c4d7 to your computer and use it in GitHub Desktop.
Python:Syntax

Metaclass

def setGreeting(self,greeting):
	self.greeting=greeting
	
	
class HelloMetaClass(type):
    def __new__(cls,class_name,base_classes,class_attributes):
	print "Class %s is being created in memory" % (class_name,)
        if  "greetAttribute" not in class_attributes.keys():
            class_attributes["greeting"]="Hello World"
	    class_attributes["setGreeting"]=setGreeting
        return super(HelloMetaClass,cls).__new__(cls,class_name,base_classes,class_attributes)
    def __init__(cls,class_name,base_classes,class_attributes):
	print "class object %s is being init" % (class_name,)
    def __call__(self,*args,**kwargs):
	print "Class object is called to create class instance object"
	return super(HelloMetaClass,self).__call__(*args,**kwargs)

class Person(object):
    __metaclass__=HelloMetaClass
    def __init__(self,name,age):
        self.name=name
        self.age=age
p=Person("Jack Nicholas",67)
print p.greeting
p.setGreeting("Whats up")
print p.greeting
p=Person("Jack Nicholas",67)

Yield & Generator

class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age
        self.children=[]
        self.currentChild=0
    def addChildName(self,childName):
        self.children.append(childName)
    def my_generator(self):
        print "Starting execution"
        while self.currentChild < len(self.children):
            yield self.children[self.currentChild]
            print "I am continuing execution"
            self.currentChild +=1
        

p=Person("Jack Sparrow",31)
p.addChildName("Davis Jones")
p.addChildName("Hector Barbossa")
p.addChildName("Will Turner")

saved_generator=p.my_generator()

for childName in saved_generator:
    print childName

saved_generator.next()

Iterable and Iterator

class Person: #iterator
    def __init__(self,name,age):
        self.name=name
        self.age=age
        self.children=[]
        self.currentChild=0
    def addChildName(self,childName):
        self.children.append(childName)
    def __iter__(self):
        return self
    def next(self):
        if self.currentChild < len(self.children):
            self.currentChild +=1
            return self.children[self.currentChild -1]
        else:
            self.currentChild =0
            raise StopIteration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment