Poppy Cooke

Poppy Cooke

1565254822

JavaScript Bind(), Call() and Apply() Explained with Examples

Understanding bind(), call() and apply() methods in JavaScript

If you are learning JavaScript, you might have seen the this keyword. The this keyword in JavaScript behaves differently compared to other programming languages. This causes a lot of confusion for programmers.

In other object-oriented programming languages, the this keyword always refers to the current instance of the class. Whereas in JavaScript, the value of this depends on how a function is called.

Let’s look at some examples to demonstrate the behavior of this in JavaScript.

Example 1:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  printName: function() {
    console.log(this.firstName + ' ' + this.lastName);
  }
};

Now let’s execute the printName method.

person.printName();

This prints:

John Doe

Here, I am calling the printName() method using the person object, so the this keyword inside the method refers to the person object.

Let’s write the below snippet at the end of the above code.

const printFullName = person.printName;
printFullName();

What do you think the console.log will now output? Surprisingly, this prints:

undefined undefined

Why does this happen?

Here, we are storing a reference of person.printName to printFullName variable. After that, we are calling it without an object reference, so this will now refer to the window (global) object or undefined (in strict mode).

If the script is in strict mode, this refers to undefined, so console.log() will return an error.

Example 2:

const counter = {
  count: 0,
  incrementCounter: function() {
    console.log(this);
    this.count++;
  }
}
document.querySelector('.btn').addEventListener('click', counter.incrementCounter);

What would be the value of this inside incrementCounter() method?

In the above snippet, the this keyword refers to the DOM element where the event happened, not the counter object.

So we can see that the this keyword inside a function refers to different objects depending on how the function is called and sometimes we accidentally lose reference to the this variable. So how can we prevent that from happening?

Call( ), Bind( ), and Apply( ) to Rescue

We use call, bind and apply methods to set the this keyword independent of how the function is called. This is especially useful for the callbacks (as in the above example).

We know that functions are a special kind of objects in JavaScript. So they have access to some methods and properties. To prove functions are objects, we can do something like this, for example:

function greeting() {
  console.log('Hello World');
}
greeting.lang = 'English';
// Prints 'English'
console.log(greeting.lang);

JavaScript also provides some special methods and properties to every function object. So every function in JavaScript inherits those methods. Call, bind, and apply are some of the methods that every function inherits.

Bind( )

The bind method creates a new function and sets the this keyword to the specified object.

Syntax:

function.bind(thisArg, optionalArguments)

For example:

Let’s suppose we have two person objects.

const john = {
  name: 'John',
  age: 24,
};
const jane = {
  name: 'Jane',
  age: 22,
};

Let’s add a greeting function:

function greeting() {
  console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
}

We can use the bind method on the greeting function to bind the this keyword to john and jane objects. For example:

const greetingJohn = greeting.bind(john);
// Hi, I am John and I am 24 years old
greetingJohn();
const greetingJane = greeting.bind(jane);
// Hi, I am Jane and I am 22 years old
greetingJane();

Here greeting.bind(john) creates a new function with this set to john object, which we then assign to greetingJohn variable. Similarly for greetingJane.

We can also use bind in case of callbacks and event handlers. For example:

const counter = {
  count: 0,
  incrementCounter: function() {
    console.log(this);
    this.count++;
  }
}
document.querySelector('.btn').addEventListener('click', counter.incrementCounter.bind(counter));

In the above example, the this keyword inside the incrementCounter method will now correctly refer to the counter object instead of the event object.

Bind() can also accept arguments

We can also pass extra arguments to the bind method. The general syntax for this is function.bind(this, arg1, arg2, ...). For example:

function greeting(lang) {
  console.log(`${lang}: I am ${this.name}`);
}
const john = {
  name: 'John'
};
const jane = {
  name: 'Jane'
};
const greetingJohn = greeting.bind(john, 'en');
greetingJohn();
const greetingJane = greeting.bind(jane, 'es');
greetingJane();

In the above example, the bind method creates a new function with certain parameters predefined (lang in this case) and this keyword set to the john and jane objects.

Call ( )

The call method sets the this inside the function and immediately executes that function.

The difference between call() and bind() is that the call() sets the this keyword and executes the function immediately and it does not create a new copy of the function, while the bind() creates a copy of that function and sets the this keyword.

Syntax:

function.call(thisArg, arg1, agr2, ...)

For example:

function greeting() {
  console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
}
const john = {
  name: 'John',
  age: 24,
};
const jane = {
  name: 'Jane',
  age: 22,
};
// Hi, I am John and I am 24 years old
greeting.call(john);
// Hi, I am Jane and I am 22 years old
greeting.call(jane);

Above example is similar to the bind() example except that call() does not create a new function. We are directly setting the this keyword using call().

Call () can also accept arguments

Call() also accepts a comma-separated list of arguments. The general syntax for this is function.call(this, arg1, arg2, ...)

For example:

function greet(greeting) {
  console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
}
const john = {
  name: 'John',
  age: 24,
};
const jane = {
  name: 'Jane',
  age: 22,
};
// Hi, I am John and I am 24 years old
greet.call(john, 'Hi');
// Hi, I am Jane and I am 22 years old
greet.call(jane, 'Hello');

Apply ( )

The apply() method is similar to call(). The difference is that the apply() method accepts an array of arguments instead of comma separated values.

Syntax:

function.apply(thisArg, [argumentsArr])

For example:

function greet(greeting, lang) {
  console.log(lang);
  console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
}
const john = {
  name: 'John',
  age: 24,
};
const jane = {
  name: 'Jane',
  age: 22,
};
// Hi, I am John and I am 24 years old
greet.apply(john, ['Hi', 'en']);
// Hi, I am Jane and I am 22 years old
greet.apply(jane, ['Hola', 'es']);

Conclusion

We have learned that how this keyword behaves differently in JavaScript than in other object-oriented languages. The call, bind and apply methods can be used to set the this keyword independent of how a function is called.

The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.

#javascript #js #programming 

 

What is GEEK

Buddha Community

JavaScript Bind(), Call() and Apply() Explained with Examples
Lawrence  Lesch

Lawrence Lesch

1677668905

TS-mockito: Mocking Library for TypeScript

TS-mockito

Mocking library for TypeScript inspired by http://mockito.org/

1.x to 2.x migration guide

1.x to 2.x migration guide

Main features

  • Strongly typed
  • IDE autocomplete
  • Mock creation (mock) (also abstract classes) #example
  • Spying on real objects (spy) #example
  • Changing mock behavior (when) via:
  • Checking if methods were called with given arguments (verify)
    • anything, notNull, anyString, anyOfClass etc. - for more flexible comparision
    • once, twice, times, atLeast etc. - allows call count verification #example
    • calledBefore, calledAfter - allows call order verification #example
  • Resetting mock (reset, resetCalls) #example, #example
  • Capturing arguments passed to method (capture) #example
  • Recording multiple behaviors #example
  • Readable error messages (ex. 'Expected "convertNumberToString(strictEqual(3))" to be called 2 time(s). But has been called 1 time(s).')

Installation

npm install ts-mockito --save-dev

Usage

Basics

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance from mock
let foo:Foo = instance(mockedFoo);

// Using instance in source code
foo.getBar(3);
foo.getBar(5);

// Explicit, readable verification
verify(mockedFoo.getBar(3)).called();
verify(mockedFoo.getBar(anything())).called();

Stubbing method calls

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub method before execution
when(mockedFoo.getBar(3)).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.getBar(3));

// prints null, because "getBar(999)" was not stubbed
console.log(foo.getBar(999));

Stubbing getter value

// Creating mock
let mockedFoo:Foo = mock(Foo);

// stub getter before execution
when(mockedFoo.sampleGetter).thenReturn('three');

// Getting instance
let foo:Foo = instance(mockedFoo);

// prints three
console.log(foo.sampleGetter);

Stubbing property values that have no getters

Syntax is the same as with getter values.

Please note, that stubbing properties that don't have getters only works if Proxy object is available (ES6).

Call count verification

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(2);
foo.getBar(2);
foo.getBar(3);

// Call count verification
verify(mockedFoo.getBar(1)).once();               // was called with arg === 1 only once
verify(mockedFoo.getBar(2)).twice();              // was called with arg === 2 exactly two times
verify(mockedFoo.getBar(between(2, 3))).thrice(); // was called with arg between 2-3 exactly three times
verify(mockedFoo.getBar(anyNumber()).times(4);    // was called with any number arg exactly four times
verify(mockedFoo.getBar(2)).atLeast(2);           // was called with arg === 2 min two times
verify(mockedFoo.getBar(anything())).atMost(4);   // was called with any argument max four times
verify(mockedFoo.getBar(4)).never();              // was never called with arg === 4

Call order verification

// Creating mock
let mockedFoo:Foo = mock(Foo);
let mockedBar:Bar = mock(Bar);

// Getting instance
let foo:Foo = instance(mockedFoo);
let bar:Bar = instance(mockedBar);

// Some calls
foo.getBar(1);
bar.getFoo(2);

// Call order verification
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(2));    // foo.getBar(1) has been called before bar.getFoo(2)
verify(mockedBar.getFoo(2)).calledAfter(mockedFoo.getBar(1));    // bar.getFoo(2) has been called before foo.getBar(1)
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(999999));    // throws error (mockedBar.getFoo(999999) has never been called)

Throwing errors

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(10)).thenThrow(new Error('fatal error'));

let foo:Foo = instance(mockedFoo);
try {
    foo.getBar(10);
} catch (error:Error) {
    console.log(error.message); // 'fatal error'
}

Custom function

You can also stub method with your own implementation

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

when(mockedFoo.sumTwoNumbers(anyNumber(), anyNumber())).thenCall((arg1:number, arg2:number) => {
    return arg1 * arg2; 
});

// prints '50' because we've changed sum method implementation to multiply!
console.log(foo.sumTwoNumbers(5, 10));

Resolving / rejecting promises

You can also stub method to resolve / reject promise

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.fetchData("a")).thenResolve({id: "a", value: "Hello world"});
when(mockedFoo.fetchData("b")).thenReject(new Error("b does not exist"));

Resetting mock calls

You can reset just mock call counter

// Creating mock
let mockedFoo:Foo = mock(Foo);

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
foo.getBar(1);
foo.getBar(1);
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
resetCalls(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset

You can also reset calls of multiple mocks at once resetCalls(firstMock, secondMock, thirdMock)

Resetting mock

Or reset mock call counter with all stubs

// Creating mock
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(1)).thenReturn("one").

// Getting instance
let foo:Foo = instance(mockedFoo);

// Some calls
console.log(foo.getBar(1));               // "one" - as defined in stub
console.log(foo.getBar(1));               // "one" - as defined in stub
verify(mockedFoo.getBar(1)).twice();      // getBar with arg "1" has been called twice

// Reset mock
reset(mockedFoo);

// Call count verification
verify(mockedFoo.getBar(1)).never();      // has never been called after reset
console.log(foo.getBar(1));               // null - previously added stub has been removed

You can also reset multiple mocks at once reset(firstMock, secondMock, thirdMock)

Capturing method arguments

let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);

// Call method
foo.sumTwoNumbers(1, 2);

// Check first arg captor values
const [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();
console.log(firstArg);    // prints 1
console.log(secondArg);    // prints 2

You can also get other calls using first(), second(), byCallIndex(3) and more...

Recording multiple behaviors

You can set multiple returning values for same matching values

const mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(anyNumber())).thenReturn('one').thenReturn('two').thenReturn('three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinitely

Another example with specific values

let mockedFoo:Foo = mock(Foo);

when(mockedFoo.getBar(1)).thenReturn('one').thenReturn('another one');
when(mockedFoo.getBar(2)).thenReturn('two');

let foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(2));    // two
console.log(foo.getBar(1));    // another one
console.log(foo.getBar(1));    // another one - this is last defined behavior for arg '1' so it will be repeated
console.log(foo.getBar(2));    // two
console.log(foo.getBar(2));    // two - this is last defined behavior for arg '2' so it will be repeated

Short notation:

const mockedFoo:Foo = mock(Foo);

// You can specify return values as multiple thenReturn args
when(mockedFoo.getBar(anyNumber())).thenReturn('one', 'two', 'three');

const foo:Foo = instance(mockedFoo);

console.log(foo.getBar(1));    // one
console.log(foo.getBar(1));    // two
console.log(foo.getBar(1));    // three
console.log(foo.getBar(1));    // three - last defined behavior will be repeated infinity

Possible errors:

const mockedFoo:Foo = mock(Foo);

// When multiple matchers, matches same result:
when(mockedFoo.getBar(anyNumber())).thenReturn('one');
when(mockedFoo.getBar(3)).thenReturn('one');

const foo:Foo = instance(mockedFoo);
foo.getBar(3); // MultipleMatchersMatchSameStubError will be thrown, two matchers match same method call

Mocking interfaces

You can mock interfaces too, just instead of passing type to mock function, set mock function generic type Mocking interfaces requires Proxy implementation

let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)
const foo: SampleGeneric<FooInterface> = instance(mockedFoo);

Mocking types

You can mock abstract classes

const mockedFoo: SampleAbstractClass = mock(SampleAbstractClass);
const foo: SampleAbstractClass = instance(mockedFoo);

You can also mock generic classes, but note that generic type is just needed by mock type definition

const mockedFoo: SampleGeneric<SampleInterface> = mock(SampleGeneric);
const foo: SampleGeneric<SampleInterface> = instance(mockedFoo);

Spying on real objects

You can partially mock an existing instance:

const foo: Foo = new Foo();
const spiedFoo = spy(foo);

when(spiedFoo.getBar(3)).thenReturn('one');

console.log(foo.getBar(3)); // 'one'
console.log(foo.getBaz()); // call to a real method

You can spy on plain objects too:

const foo = { bar: () => 42 };
const spiedFoo = spy(foo);

foo.bar();

console.log(capture(spiedFoo.bar).last()); // [42] 

Thanks


Download Details:

Author: NagRock
Source Code: https://github.com/NagRock/ts-mockito 
License: MIT license

#typescript #testing #mock 

Python Global Variables – How to Define a Global Variable Example

In this article, you will learn the basics of global variables.

To begin with, you will learn how to declare variables in Python and what the term 'variable scope' actually means.

Then, you will learn the differences between local and global variables and understand how to define global variables and how to use the global keyword.

What Are Variables in Python and How Do You Create Them? An Introduction for Beginners

You can think of variables as storage containers.

They are storage containers for holding data, information, and values that you would like to save in the computer's memory. You can then reference or even manipulate them at some point throughout the life of the program.

A variable has a symbolic name, and you can think of that name as the label on the storage container that acts as its identifier.

The variable name will be a reference and pointer to the data stored inside it. So, there is no need to remember the details of your data and information – you only need to reference the variable name that holds that data and information.

When giving a variable a name, make sure that it is descriptive of the data it holds. Variable names need to be clear and easily understandable both for your future self and the other developers you may be working with.

Now, let's see how to actually create a variable in Python.

When declaring variables in Python, you don't need to specify their data type.

For example, in the C programming language, you have to mention explicitly the type of data the variable will hold.

So, if you wanted to store your age which is an integer, or int type, this is what you would have to do in C:

#include <stdio.h>
 
int main(void)
{
  int age = 28;
  // 'int' is the data type
  // 'age' is the name 
  // 'age' is capable of holding integer values
  // positive/negative whole numbers or 0
  // '=' is the assignment operator
  // '28' is the value
}

However, this is how you would write the above in Python:

age = 28

#'age' is the variable name, or identifier
# '=' is the assignment operator
#'28' is the value assigned to the variable, so '28' is the value of 'age'

The variable name is always on the left-hand side, and the value you want to assign goes on the right-hand side after the assignment operator.

Keep in mind that you can change the values of variables throughout the life of a program:

my_age = 28

print(f"My age in 2022 is {my_age}.")

my_age = 29

print(f"My age in 2023 will be {my_age}.")

#output

#My age in 2022 is 28.
#My age in 2023 will be 29.

You keep the same variable name, my_age, but only change the value from 28 to 29.

What Does Variable Scope in Python Mean?

Variable scope refers to the parts and boundaries of a Python program where a variable is available, accessible, and visible.

There are four types of scope for Python variables, which are also known as the LEGB rule:

  • Local,
  • Enclosing,
  • Global,
  • Built-in.

For the rest of this article, you will focus on learning about creating variables with global scope, and you will understand the difference between the local and global variable scopes.

How to Create Variables With Local Scope in Python

Variables defined inside a function's body have local scope, which means they are accessible only within that particular function. In other words, they are 'local' to that function.

You can only access a local variable by calling the function.

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()


#output

#The best place to learn to code is with freeCodeCamp!

Look at what happens when I try to access that variable with a local scope from outside the function's body:

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#try to print local variable 'coding_website' from outside the function
print(coding_website)

#output

#NameError: name 'coding_website' is not defined

It raises a NameError because it is not 'visible' in the rest of the program. It is only 'visible' within the function where it was defined.

How to Create Variables With Global Scope in Python

When you define a variable outside a function, like at the top of the file, it has a global scope and it is known as a global variable.

A global variable is accessed from anywhere in the program.

You can use it inside a function's body, as well as access it from outside a function:

#create a global variable
coding_website = "freeCodeCamp"

def learn_to_code():
    #access the variable 'coding_website' inside the function
    print(f"The best place to learn to code is with {coding_website}!")

#call the function
learn_to_code()

#access the variable 'coding_website' from outside the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

What happens when there is a global and local variable, and they both have the same name?

#global variable
city = "Athens"

def travel_plans():
    #local variable with the same name as the global variable
    city = "London"
    print(f"I want to visit {city} next year!")

#call function - this will output the value of local variable
travel_plans()

#reference global variable - this will output the value of global variable
print(f"I want to visit {city} next year!")

#output

#I want to visit London next year!
#I want to visit Athens next year!

In the example above, maybe you were not expecting that specific output.

Maybe you thought that the value of city would change when I assigned it a different value inside the function.

Maybe you expected that when I referenced the global variable with the line print(f" I want to visit {city} next year!"), the output would be #I want to visit London next year! instead of #I want to visit Athens next year!.

However, when the function was called, it printed the value of the local variable.

Then, when I referenced the global variable outside the function, the value assigned to the global variable was printed.

They didn't interfere with one another.

That said, using the same variable name for global and local variables is not considered a best practice. Make sure that your variables don't have the same name, as you may get some confusing results when you run your program.

How to Use the global Keyword in Python

What if you have a global variable but want to change its value inside a function?

Look at what happens when I try to do that:

#global variable
city = "Athens"

def travel_plans():
    #First, this is like when I tried to access the global variable defined outside the function. 
    # This works fine on its own, as you saw earlier on.
    print(f"I want to visit {city} next year!")

    #However, when I then try to re-assign a different value to the global variable 'city' from inside the function,
    #after trying to print it,
    #it will throw an error
    city = "London"
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#output

#UnboundLocalError: local variable 'city' referenced before assignment

By default Python thinks you want to use a local variable inside a function.

So, when I first try to print the value of the variable and then re-assign a value to the variable I am trying to access, Python gets confused.

The way to change the value of a global variable inside a function is by using the global keyword:

#global variable
city = "Athens"

#print value of global variable
print(f"I want to visit {city} next year!")

def travel_plans():
    global city
    #print initial value of global variable
    print(f"I want to visit {city} next year!")
    #assign a different value to global variable from within function
    city = "London"
    #print new value
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#print value of global variable
print(f"I want to visit {city} next year!")

Use the global keyword before referencing it in the function, as you will get the following error: SyntaxError: name 'city' is used prior to global declaration.

Earlier, you saw that you couldn't access variables created inside functions since they have local scope.

The global keyword changes the visibility of variables declared inside functions.

def learn_to_code():
   global coding_website
   coding_website = "freeCodeCamp"
   print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()

#access variable from within the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

Conclusion

And there you have it! You now know the basics of global variables in Python and can tell the differences between local and global variables.

I hope you found this article useful.

You'll start from the basics and learn in an interactive and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you've learned.

Thanks for reading and happy coding!

Source: https://www.freecodecamp.org/news/python-global-variables-examples/

#python 

Tanya  Shields

Tanya Shields

1594896120

JavaScript tutorial - call, apply and bind methods in JavaScript

Working with JavaScript “this” keyword can be tricky. Not knowing the background rules may end up with the famous “it works, but I don’t know why” or worse: “it doesn’t work and I don’t know why”. It’s good to know the theory before putting things into practice. Call(), Apply() and Bind() methods can come in handy when setting the “this” value.
This tutorial covers call(), apply() and bind() methods. A multiple basic examples have been provided.

Basic rules worth remembering:

  1. “this” always refers to an object.
  2. “this” refers to an object which calls the function it contains.
  3. In the global context “this” refers to either window object or is undefined if the ‘strict mode’ is used.
var car = { 
    registrationNumber: "GA12345",
    brand: "Toyota",

    displayDetails: function(){
        console.log(this.registrationNumber + " " + this.brand);
    }
}

The above will work perfectly fine as long as we use it this way:

car.displayDetails(); // GA12345 Toyota

But what if we want to borrow a method?

var myCarDetails =  car.displayDetails;
myCarDetails();

Well, this won’t work as the “this” will be now assigned to the global context which doesn’t have neither the registrationNumber nor the brand property.

#javascript #programming #call #apply #bind methods

Variables Globales De Python: Cómo Definir Un Ejemplo De Variable Glob

En este artículo, aprenderá los conceptos básicos de las variables globales.

Para empezar, aprenderá cómo declarar variables en Python y qué significa realmente el término 'ámbito de variable'.

Luego, aprenderá las diferencias entre variables locales y globales y comprenderá cómo definir variables globales y cómo usar la globalpalabra clave.

¿Qué son las variables en Python y cómo se crean? Una introducción para principiantes

Puede pensar en las variables como contenedores de almacenamiento .

Son contenedores de almacenamiento para almacenar datos, información y valores que le gustaría guardar en la memoria de la computadora. Luego puede hacer referencia a ellos o incluso manipularlos en algún momento a lo largo de la vida del programa.

Una variable tiene un nombre simbólico y puede pensar en ese nombre como la etiqueta en el contenedor de almacenamiento que actúa como su identificador.

El nombre de la variable será una referencia y un puntero a los datos almacenados en su interior. Por lo tanto, no es necesario recordar los detalles de sus datos e información; solo necesita hacer referencia al nombre de la variable que contiene esos datos e información.

Al dar un nombre a una variable, asegúrese de que sea descriptivo de los datos que contiene. Los nombres de las variables deben ser claros y fácilmente comprensibles tanto para usted en el futuro como para los otros desarrolladores con los que puede estar trabajando.

Ahora, veamos cómo crear una variable en Python.

Al declarar variables en Python, no necesita especificar su tipo de datos.

Por ejemplo, en el lenguaje de programación C, debe mencionar explícitamente el tipo de datos que contendrá la variable.

Entonces, si quisiera almacenar su edad, que es un número entero, o inttipo, esto es lo que tendría que hacer en C:

#include <stdio.h>
 
int main(void)
{
  int age = 28;
  // 'int' is the data type
  // 'age' is the name 
  // 'age' is capable of holding integer values
  // positive/negative whole numbers or 0
  // '=' is the assignment operator
  // '28' is the value
}

Sin embargo, así es como escribirías lo anterior en Python:

age = 28

#'age' is the variable name, or identifier
# '=' is the assignment operator
#'28' is the value assigned to the variable, so '28' is the value of 'age'

El nombre de la variable siempre está en el lado izquierdo y el valor que desea asignar va en el lado derecho después del operador de asignación.

Tenga en cuenta que puede cambiar los valores de las variables a lo largo de la vida de un programa:

my_age = 28

print(f"My age in 2022 is {my_age}.")

my_age = 29

print(f"My age in 2023 will be {my_age}.")

#output

#My age in 2022 is 28.
#My age in 2023 will be 29.

Mantienes el mismo nombre de variable my_age, pero solo cambias el valor de 28a 29.

¿Qué significa el alcance variable en Python?

El alcance de la variable se refiere a las partes y los límites de un programa de Python donde una variable está disponible, accesible y visible.

Hay cuatro tipos de alcance para las variables de Python, que también se conocen como la regla LEGB :

  • local ,
  • Encerrando ,
  • globales ,
  • Incorporado .

En el resto de este artículo, se centrará en aprender a crear variables con alcance global y comprenderá la diferencia entre los alcances de variables locales y globales.

Cómo crear variables con alcance local en Python

Las variables definidas dentro del cuerpo de una función tienen alcance local , lo que significa que solo se puede acceder a ellas dentro de esa función en particular. En otras palabras, son 'locales' para esa función.

Solo puede acceder a una variable local llamando a la función.

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()


#output

#The best place to learn to code is with freeCodeCamp!

Mire lo que sucede cuando trato de acceder a esa variable con un alcance local desde fuera del cuerpo de la función:

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#try to print local variable 'coding_website' from outside the function
print(coding_website)

#output

#NameError: name 'coding_website' is not defined

Plantea un NameErrorporque no es 'visible' en el resto del programa. Solo es 'visible' dentro de la función donde se definió.

Cómo crear variables con alcance global en Python

Cuando define una variable fuera de una función, como en la parte superior del archivo, tiene un alcance global y se conoce como variable global.

Se accede a una variable global desde cualquier parte del programa.

Puede usarlo dentro del cuerpo de una función, así como acceder desde fuera de una función:

#create a global variable
coding_website = "freeCodeCamp"

def learn_to_code():
    #access the variable 'coding_website' inside the function
    print(f"The best place to learn to code is with {coding_website}!")

#call the function
learn_to_code()

#access the variable 'coding_website' from outside the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

¿Qué sucede cuando hay una variable global y local, y ambas tienen el mismo nombre?

#global variable
city = "Athens"

def travel_plans():
    #local variable with the same name as the global variable
    city = "London"
    print(f"I want to visit {city} next year!")

#call function - this will output the value of local variable
travel_plans()

#reference global variable - this will output the value of global variable
print(f"I want to visit {city} next year!")

#output

#I want to visit London next year!
#I want to visit Athens next year!

En el ejemplo anterior, tal vez no esperaba ese resultado específico.

Tal vez pensaste que el valor de citycambiaría cuando le asignara un valor diferente dentro de la función.

Tal vez esperabas que cuando hice referencia a la variable global con la línea print(f" I want to visit {city} next year!"), la salida sería en #I want to visit London next year!lugar de #I want to visit Athens next year!.

Sin embargo, cuando se llamó a la función, imprimió el valor de la variable local.

Luego, cuando hice referencia a la variable global fuera de la función, se imprimió el valor asignado a la variable global.

No interfirieron entre sí.

Dicho esto, usar el mismo nombre de variable para variables globales y locales no se considera una buena práctica. Asegúrese de que sus variables no tengan el mismo nombre, ya que puede obtener algunos resultados confusos cuando ejecute su programa.

Cómo usar la globalpalabra clave en Python

¿Qué sucede si tiene una variable global pero desea cambiar su valor dentro de una función?

Mira lo que sucede cuando trato de hacer eso:

#global variable
city = "Athens"

def travel_plans():
    #First, this is like when I tried to access the global variable defined outside the function. 
    # This works fine on its own, as you saw earlier on.
    print(f"I want to visit {city} next year!")

    #However, when I then try to re-assign a different value to the global variable 'city' from inside the function,
    #after trying to print it,
    #it will throw an error
    city = "London"
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#output

#UnboundLocalError: local variable 'city' referenced before assignment

Por defecto, Python piensa que quieres usar una variable local dentro de una función.

Entonces, cuando intento imprimir el valor de la variable por primera vez y luego reasignar un valor a la variable a la que intento acceder, Python se confunde.

La forma de cambiar el valor de una variable global dentro de una función es usando la globalpalabra clave:

#global variable
city = "Athens"

#print value of global variable
print(f"I want to visit {city} next year!")

def travel_plans():
    global city
    #print initial value of global variable
    print(f"I want to visit {city} next year!")
    #assign a different value to global variable from within function
    city = "London"
    #print new value
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#print value of global variable
print(f"I want to visit {city} next year!")

Utilice la globalpalabra clave antes de hacer referencia a ella en la función, ya que obtendrá el siguiente error: SyntaxError: name 'city' is used prior to global declaration.

Anteriormente, vio que no podía acceder a las variables creadas dentro de las funciones ya que tienen un alcance local.

La globalpalabra clave cambia la visibilidad de las variables declaradas dentro de las funciones.

def learn_to_code():
   global coding_website
   coding_website = "freeCodeCamp"
   print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()

#access variable from within the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

Conclusión

¡Y ahí lo tienes! Ahora conoce los conceptos básicos de las variables globales en Python y puede distinguir las diferencias entre las variables locales y globales.

Espero que hayas encontrado útil este artículo.

Comenzará desde lo básico y aprenderá de una manera interactiva y amigable para principiantes. También construirá cinco proyectos al final para poner en práctica y ayudar a reforzar lo que ha aprendido.

¡Gracias por leer y feliz codificación!

Fuente: https://www.freecodecamp.org/news/python-global-variables-examples/

#python 

坂本  篤司

坂本 篤司

1652450700

Pythonグローバル変数–グローバル変数の例を定義する方法

この記事では、グローバル変数の基本を学びます。

まず、Pythonで変数を宣言する方法と、「変数スコープ」という用語が実際に何を意味するかを学習します。

次に、ローカル変数とグローバル変数の違いを学び、グローバル変数の定義方法とglobalキーワードの使用方法を理解します。

Pythonの変数とは何ですか?どのように作成しますか?初心者のための紹介

変数はストレージコンテナと考えることができます。

これらは、コンピュータのメモリに保存したいデータ、情報、および値を保持するためのストレージコンテナです。その後、プログラムの存続期間中のある時点でそれらを参照したり、操作したりすることもできます。

変数にはシンボリックがあり、その名前は、その識別子として機能するストレージコンテナのラベルと考えることができます。

変数名は、その中に格納されているデータへの参照とポインターになります。したがって、データと情報の詳細を覚えておく必要はありません。そのデータと情報を保持する変数名を参照するだけで済みます。

変数に名前を付けるときは、変数が保持するデータを説明していることを確認してください。変数名は、将来の自分自身と一緒に作業する可能性のある他の開発者の両方にとって、明確で簡単に理解できる必要があります。

それでは、Pythonで実際に変数を作成する方法を見てみましょう。

Pythonで変数を宣言するときは、データ型を指定する必要はありません。

たとえば、Cプログラミング言語では、変数が保持するデータの型を明示的に指定する必要があります。

したがって、整数またはint型である年齢を格納したい場合、これはCで行う必要があることです。

#include <stdio.h>
 
int main(void)
{
  int age = 28;
  // 'int' is the data type
  // 'age' is the name 
  // 'age' is capable of holding integer values
  // positive/negative whole numbers or 0
  // '=' is the assignment operator
  // '28' is the value
}

ただし、これはPythonで上記を記述する方法です。

age = 28

#'age' is the variable name, or identifier
# '=' is the assignment operator
#'28' is the value assigned to the variable, so '28' is the value of 'age'

変数名は常に左側にあり、代入する値は代入演算子の後に右側に配置されます。

プログラムの存続期間中、変数の値を変更できることに注意してください。

my_age = 28

print(f"My age in 2022 is {my_age}.")

my_age = 29

print(f"My age in 2023 will be {my_age}.")

#output

#My age in 2022 is 28.
#My age in 2023 will be 29.

同じ変数名を保持しますが、値をからにmy_age変更するだけです。2829

Pythonの可変スコープとはどういう意味ですか?

変数スコープとは、変数が利用可能で、アクセス可能で、表示可能なPythonプログラムの部分と境界を指します。

Python変数のスコープには4つのタイプがあり、 LEGBルールとも呼ばれます。

  • 局所
  • 囲み
  • グローバル
  • ビルトイン

この記事の残りの部分では、グローバルスコープを使用した変数の作成について学習することに焦点を当て、ローカル変数スコープとグローバル変数スコープの違いを理解します。

Pythonでローカルスコープを使用して変数を作成する方法

関数の本体内で定義された変数にはローカルスコープがあります。つまり、その特定の関数内でのみアクセスできます。言い換えれば、それらはその関数に対して「ローカル」です。

ローカル変数にアクセスするには、関数を呼び出す必要があります。

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()


#output

#The best place to learn to code is with freeCodeCamp!

関数の本体の外部からローカルスコープを使用してその変数にアクセスしようとするとどうなるかを見てください。

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#try to print local variable 'coding_website' from outside the function
print(coding_website)

#output

#NameError: name 'coding_website' is not defined

NameErrorプログラムの残りの部分では「表示」されないため、aが発生します。定義された関数内でのみ「表示」されます。

Pythonでグローバルスコープを使用して変数を作成する方法

ファイルの先頭など、関数の外部で変数を定義すると、その変数はグローバルスコープを持ち、グローバル変数と呼ばれます。

グローバル変数は、プログラムのどこからでもアクセスできます。

関数の本体内で使用することも、関数の外部からアクセスすることもできます。

#create a global variable
coding_website = "freeCodeCamp"

def learn_to_code():
    #access the variable 'coding_website' inside the function
    print(f"The best place to learn to code is with {coding_website}!")

#call the function
learn_to_code()

#access the variable 'coding_website' from outside the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

グローバル変数とローカル変数があり、両方が同じ名前の場合はどうなりますか?

#global variable
city = "Athens"

def travel_plans():
    #local variable with the same name as the global variable
    city = "London"
    print(f"I want to visit {city} next year!")

#call function - this will output the value of local variable
travel_plans()

#reference global variable - this will output the value of global variable
print(f"I want to visit {city} next year!")

#output

#I want to visit London next year!
#I want to visit Athens next year!

上記の例では、その特定の出力を期待していなかった可能性があります。

city関数内で別の値を割り当てたときに、の値が変わると思ったかもしれません。

たぶん、私が行でグローバル変数を参照したときprint(f" I want to visit {city} next year!")、出力は#I want to visit London next year!の代わりになると予想しました#I want to visit Athens next year!

ただし、関数が呼び出されると、ローカル変数の値が出力されます。

次に、関数の外部でグローバル変数を参照すると、グローバル変数に割り当てられた値が出力されました。

彼らはお互いに干渉しませんでした。

ただし、グローバル変数とローカル変数に同じ変数名を使用することは、ベストプラクティスとは見なされません。プログラムを実行すると混乱する結果が生じる可能性があるため、変数の名前が同じでないことを確認してください。

Pythonでキーワードを使用する方法global

グローバル変数があり、関数内でその値を変更したい場合はどうなりますか?

私がそれをしようとすると何が起こるか見てください:

#global variable
city = "Athens"

def travel_plans():
    #First, this is like when I tried to access the global variable defined outside the function. 
    # This works fine on its own, as you saw earlier on.
    print(f"I want to visit {city} next year!")

    #However, when I then try to re-assign a different value to the global variable 'city' from inside the function,
    #after trying to print it,
    #it will throw an error
    city = "London"
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#output

#UnboundLocalError: local variable 'city' referenced before assignment

デフォルトでは、Pythonは関数内でローカル変数を使用したいと考えています。

そのため、最初に変数の値を出力してから、アクセスしようとしている変数に値再割り当てしようとすると、Pythonが混乱します。

関数内のグローバル変数の値を変更する方法は、次のglobalキーワードを使用することです。

#global variable
city = "Athens"

#print value of global variable
print(f"I want to visit {city} next year!")

def travel_plans():
    global city
    #print initial value of global variable
    print(f"I want to visit {city} next year!")
    #assign a different value to global variable from within function
    city = "London"
    #print new value
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#print value of global variable
print(f"I want to visit {city} next year!")

global次のエラーが発生するため、関数でキーワードを参照する前にキーワードを使用してくださいSyntaxError: name 'city' is used prior to global declaration

以前、関数内で作成された変数はローカルスコープを持っているため、それらにアクセスできないことを確認しました。

globalキーワードは、関数内で宣言された変数の可視性を変更します。

def learn_to_code():
   global coding_website
   coding_website = "freeCodeCamp"
   print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()

#access variable from within the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

結論

そして、あなたはそれを持っています!これで、Pythonのグローバル変数の基本を理解し、ローカル変数とグローバル変数の違いを理解できます。

この記事がお役に立てば幸いです。

基本から始めて、インタラクティブで初心者に優しい方法で学びます。また、最後に5つのプロジェクトを構築して実践し、学んだことを強化するのに役立てます。

読んでくれてありがとう、そして幸せなコーディング!

ソース:https ://www.freecodecamp.org/news/python-global-variables-examples/

#python