UrbanPro

Learn Python Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Why are default values shared between objects?

Asked by Last Modified  

Follow 0
Answer

Please enter your answer

Educate! Being smart is great!!!

By definition, immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion. Because of this feature, it is good programming practice to not use mutable objects as default values....
read more
By definition, immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion. Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use None as the default value and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is. Default values are created by the def statement, not when the function is called. Consider this function: def foo(D={}): # Danger: shared reference to one dict for all calls ... compute something ... D[key] = value return D The first time you call this function, D contains a single item. The second time, D contains two items because when foo() begins executing, D starts out with an item already in it. It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined (by executing the def statement). If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object. This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called memoizing, and can be implemented like this: # Callers will never provide a third parameter for this function. def expensive(arg1, arg2, _cache={}): if _cache.has_key((arg1, arg2)): return _cache[(arg1, arg2)] # Calculate the value result = ... expensive computation ... _cache[(arg1, arg2)] = result # Store result in the cache return result You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste. You can also use default arguments to bind local variables to objects rather than names. The first loop in the following example creates a new callback for each slot, but all callbacks end up with reference to the outer variable slot. In the second loop, explicit object binding is used to bind to the current value instead: for slot in range(10): def callback(): print "called from slot", slot # This always prints "9" register_callback(slot, callback) for slot in range(10): def callback(slot=slot): print "called from slot", slot register_callback(slot, callback) # This does the right thing read less
Comments

Related Questions

What's the coolest thing you've done with Python?
Make a fun game
J.k.kavyadharshini
0 0
5
How can I easily learn Python?
UrbanPro does not allow naming a website in answer so I have to write in this way. 'sololearnDOTcom/Course/python' is the website you can follow for easily learning python3. Its like playing a game over there.
Aditi
0 0
6
Is it possible to learn Python without any coaching class?
Certainly it is possible. What is required is some dedicated time, self-discipline and the willingness to learn by trial and error.
Neetu
0 0
7
SVM is applicable only for numeric data or can also be for textual data?
Any learning algorithm for that matter does not work Directly on text. It needs to be converted to a structured matrix before applying algorithms.The methods involve - 1. Extensive cleaning of the data...
Harsha
Should I learn a Python course online or offline? What are some good Python training classes?
If it is that much simple as i have been said to learn from the internet then everyone would have been developer according to me you should learn offline by some good institute. like Praxware technologies...
Neha
0 0
8

Now ask question in any of the 1000+ Categories, and get Answers from Tutors and Trainers on UrbanPro.com

Ask a Question

Related Lessons

Simulation of a die-roll:Usage of random module
Task:Simulation of a simple die-rolling game,where we keep rolling a six-sided die until we have rolled a total of 20. To simulate a six-sided die roll, we need a way to generate a random integer between...

Be prepared to get trained--init
Before starting the training,students must be mentally prepared for acceptance of new knowledge. Students must attend training with open minded forgetting the position they are working.This will help...
S

Smartnub Softsolutions

0 0
0

DBMS - SQL - Any/All
All - Operator SELECT empno, sal FROM emp WHERE sal > ALL (1999, 2999, 3999); Output of Above query is same as below query SELECT empno, sal FROM emp WHERE sal > 1999 AND sal > 2999...

Radhe Shyam

0 0
0

Python Introduction
Python is an object-oriented programming language created by Rossum in 1989. It is ideally designed for rapid prototyping of complex applications. It has interfaces to many OS system calls and libraries...
I

Imran

0 0
0

Recommended Articles

Python is one of the most popular programming languages in the world. It is general-purpose, object oriented, high-level programming language used in a number of programming fields. Python is a great programming language to learn as it will introduce you to the world of programming. If you are from the technical background...

Read full article >

Applications engineering is a hot trend in the current IT market.  An applications engineer is responsible for designing and application of technology products relating to various aspects of computing. To accomplish this, he/she has to work collaboratively with the company’s manufacturing, marketing, sales, and customer...

Read full article >

Software Development has been one of the most popular career trends since years. The reason behind this is the fact that software are being used almost everywhere today.  In all of our lives, from the morning’s alarm clock to the coffee maker, car, mobile phone, computer, ATM and in almost everything we use in our daily...

Read full article >

Hadoop is a framework which has been developed for organizing and analysing big chunks of data for a business. Suppose you have a file larger than your system’s storage capacity and you can’t store it. Hadoop helps in storing bigger files than what could be stored on one particular server. You can therefore store very,...

Read full article >

Looking for Python Training classes?

Learn from the Best Tutors on UrbanPro

Are you a Tutor or Training Institute?

Join UrbanPro Today to find students near you
X

Looking for Python Training Classes?

The best tutors for Python Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Python Training with the Best Tutors

The best Tutors for Python Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more