Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this interface syntax mean in python?

I am doing cs224n's assignment.In function test_word2vec, there is some python syntax I don not understand:

""" Interface to the dataset for negative sampling """
dataset = type('dummy', (), {})()
def dummySampleTokenIdx():
    return random.randint(0, 4)

def getRandomContext(C):
    tokens = ["a", "b", "c", "d", "e"]
    return tokens[random.randint(0,4)], \
        [tokens[random.randint(0,4)] for i in xrange(2*C)]
dataset.sampleTokenIdx = dummySampleTokenIdx
dataset.getRandomContext = getRandomContext

Question one: What does dataset = type('dummy', (), {})() mean ?

Question two: In dataset.sampleTokenIdx = dummySampleTokenIdx , I do not think dataset has attribute sampleTokenIdx . So, why can dataset invoke it ?

like image 232
Rachel Jennifer Avatar asked Sep 12 '26 22:09

Rachel Jennifer


1 Answers

  1. The type function with 3 arguments creates a class. So that would be equivalent to this code:

class dummy(object): pass

  1. In Python you can add an attribute to an object at any time. If it doesn't exist already, it will get created, essentially inserted into a dict that represents the object's attributes.
like image 165
Kat Avatar answered Sep 14 '26 11:09

Kat