2

Below code is creating a dictionary(foo) and then adding a method(bar) and property by name ack in that dictionary.

var foo = {};
foo.bar = function(){
     this.ack=3;
};
foo.bar();

In python, if i try doing the same,

>>> foo = {}
>>> def f():
    this.ack=3

>>> foo.bar = f
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    foo.bar = f
AttributeError: 'dict' object has no attribute 'bar'

My question:

  1. Instead of (key, value) pairs, How can JavaScript allow a method(bar) become a member of dictionary?

  2. In addition, How can JavaScript allow name ack with value 3(this is not key-value) become a member of dictionary?

2
  • There are apples and there are oranges :) Commented Apr 15, 2014 at 15:18
  • @thefourtheye i did not get you Commented Apr 15, 2014 at 15:22

5 Answers 5

2

Instead of (key, value) pairs, How can JavaScript allow a method(bar) become a member of dictionary?

In JavaScript, when you say

var foo = {};

you are creating an object and when you assign something like

foo.bar = function(){
     this.ack=3;
};

it first looks for bar in foo. If it doesn't it, it creates a new attribute and stores function object in it. Here, key is bar and the value is the function object.

But in Python, you are doing something which is entirely different. You are using a dictionary object and when you do foo.bar, it looks for bar attribute in the dictionary object, as it doesn't find it, it errors out immediately.

AttributeError: 'dict' object has no attribute 'bar'

If you are looking for a similar behaviour in Python, use objects like this

class TempClass(object):
    pass

foo = TempClass()
def function():
    ack = 3
foo.f = function

In addition, How can JavaScript allow name ack with value 3(this is not key-value) become a member of dictionary?

Now, you are messing with the this object. The this binding happens very lately. When you invoke ack, it checks the object on which ack was invoked. Since it is on foo object, this will be set to foo. So, you are creating a new attribute ack on foo indirectly.

Sign up to request clarification or add additional context in comments.

6 Comments

so in javascript, we are creating objects and their hierarchy(inheritance) without help of classes and in python we create objects with help of classes. Coming from java background(despite static language) how do u feel about thiS? Dont we have standard about OOP paradigm on what an object is? Does class suppose to exist before creating an object? Does access specifiers require for class members and methods? can we add dynamic attributes to an object? do u think these concepts became language specific?
@Sham Apart from the idea of everything is an object, Python's objects have to be created from classes. So classes have to created before the objects. We don't have access specifiers in Python.
but on another level javascript allows us to create objects without help of classes. And introduced prototypical inheritance for creating hierarchy.
@Sham That is why I said you are comparing apples and oranges :)
oh ok ): i guess, apple and orange in the aspect of programming style difference for the same oop paradigm in both languages. i think, the only answer i would get if i dont like this is, write your own interpreter. But i guess there is no choice of selecting an apple or orange because javascript is the only browser language and python is not a bad choice for server side programmin
|
1

JavaScript has no dictionary type. What you create whith {} is an Object. You can assign properties to the object like:

var foo = {};
foo.func1 = function () {};
foo['func2'] = function () {};
var a = 'func3';
foo[a] = function () {};

1 Comment

Don't forget the good old (function (o) {o.baz = 'hello';}(foo)); and (function () {this.fizz = 'world'}).call(foo);
1

First of all, don't think of a JavaScript {} as a dict. It's an Object which is closer to Python's class.

You can add methods to instances of Classes like this

from types import MethodType as bind

class Foo():
    pass

def bar(self):
    self.ack = 3

foo = Foo()
foo.bar = bind(bar, foo) # add method bar to foo as property bar
foo.bar()
foo.ack # 3

In Python it's actually "easier" to set up inheritance as you don't need to import anything

Foo.baz = bar
foo.baz() # invokes inherited bar as expected

Comments

0

I think you are confusing dictionaries, objects, and object properties. In javascript, var foo = {}; is an object. You access attributes of that object via foo.bar; In python, foo = {} is a dictionary, not an object. When you say foo.bar in python, that doesn't make any sense because a dictionary doesn't have an instance variable named bar.

Python can store function references inside of dictionaries though:

>>> foo['bar'] = lambda x: x*x
>>> foo['bar'](10);
100

3 Comments

picky-mode: "foo = {} is a dictionary, not an object." - f = {}; f.__class__.__base__ <type 'object'>
Yeah that's picky mode alright, but I accept that when most everything is an object, dictionaries are too. Makes me wonder why primitive numbers aren't also objects.
Try (5).__class__ ... 5.__class__ is an invalid floating-point literal.
0

The {} in JavaScript is an object, and when you write:

foo.bar = function(){}; // property/method-name : value

It sets the bar method of the object foo, and:

foo.name = "Something"; // property/method-name : value

sets the name property of foo object to "Something".

The {} in Python is a dictionary, and in it you do:

foo = {}

def f():
    foo["ack"] = 3 # key-value here

foo["bar"] = f

foo["bar"]()

print foo["ack"] # 3

And if you want to replicate the behaviour of dots in Python, use:

class Foo:  # constructor for objects
    pass

def f(self):      # `self` = object
    self.ack = 3  # object has properties

obj = Foo()  # object

obj.bar = f # object has methods

# passing object as parameter,
# or you need to do `bind` as illustrated by Paul S. in his answer
obj.bar(obj)  

print obj.ack # 3

2 Comments

gaurang is it 'def f(): this.ack = 3' ?
@Sham Oh, that was a typo. Thanks for notifying.

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.