3

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 ?

1 Answer 1

5
  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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.