Skip to content
Advertisement

Tag: scope

Python: Function scope inside a class

Let’s consider the code below. On first look, one might expect list_1 and list_2 to both have the same content: [“Tom”, “Tom”], but this is not the case. list_1 evaluates to [“Tom”, “Tom”], whereas list_2 evaluates to [“John”, “John”]. I read that when a function is nested inside a class, Python will use variables defined in the module scope and

Confusion about scoping in python classes

I am currently reviewing the python tutorials of python.org. I come from C++ and in the Classes tutorial (https://docs.python.org/3/tutorial/classes.html) I see that the scoping is similar to that in C++. It says the following about scoping and nesting: “At any time during execution, there are at least three nested scopes whose namespaces are directly accessible: – the innermost scope, which

How to make a variable inside a try/except block public?

How can I make a variable inside the try/except block public? This code returns an error How can I make the variable text available outside of the try/except block? Answer try statements do not create a new scope, but text won’t be set if the call to url lib.request.urlopen raises the exception. You probably want the print(text) line in an

How to access outer class from an inner class?

I have a situation like so… How can I access the Outer class’s method from the Inner class? Answer The methods of a nested class cannot directly access the instance attributes of the outer class. Note that it is not necessarily the case that an instance of the outer class exists even when you have created an instance of the

Advertisement