Python: Regarding variable scope. Why dont I need to pass x to Y?

2024/11/16 23:52:48

Consider the following code, why don't I need to pass x to Y?

class X:    def __init__(self):self.a = 1self.b = 2self.c = 3class Y:        def A(self):print(x.a,x.b,x.c)x = X()
y = Y()
y.A()

Thank you to the top answers, they really helped me see what was the problem, namely misunderstanding regarding variable scope. I wish I could choose both as correct answer as they are enlightening in their own way.

Answer

When python compiles a def into a function, it tries to figure out if the things you are referencing are locals - and if they're not, you must be referring to a global. For example:

def f():print(x)

Well, you haven't defined x within the scope of f, so you must be referring to a global.

This is all that's happening in your above code. You haven't defined x within the scope of A, so x must be a global. As it happens, you define the global:

x = X()

before you call it:

y = Y()
y.A()

so everything works out okay.

In case you are going "hm, I'm not sure if I believe you, roippi" just look at the bytecode:

dis.dis(Y.A)3           0 LOAD_GLOBAL              0 (print) 3 LOAD_GLOBAL              1 (x) # aha6 LOAD_ATTR                2 (a) 9 LOAD_GLOBAL              1 (x) # aha!12 LOAD_ATTR                3 (b) 15 LOAD_GLOBAL              1 (x) # aha!!18 LOAD_ATTR                4 (c) 21 CALL_FUNCTION            3 (3 positional, 0 keyword pair) 24 POP_TOP              25 LOAD_CONST               0 (None) 28 RETURN_VALUE     

aha.

https://en.xdnf.cn/q/71286.html

Related Q&A

Python/Pandas - partitioning a pandas DataFrame in 10 disjoint, equally-sized subsets

I want to partition a pandas DataFrame into ten disjoint, equally-sized, randomly composed subsets. I know I can randomly sample one tenth of the original pandas DataFrame using:partition_1 = pandas.Da…

How to fix pylint error Unnecessary use of a comprehension

With python 3.8.6 and pylint 2.4.4 the following code produces a pylint error (or recommendation) R1721: Unnecessary use of a comprehension (unnecessary-comprehension)This is the code: dict1 = {"A…

conv2d_transpose is dependent on batch_size when making predictions

I have a neural network currently implemented in tensorflow, but I am having a problem making predictions after training, because I have a conv2d_transpose operations, and the shapes of these ops are d…

How SelectKBest (chi2) calculates score?

I am trying to find the most valuable features by applying feature selection methods to my dataset. Im using the SelectKBest function for now. I can generate the score values and sort them as I want, b…

Refer to multiple Models in View/Template in Django

Im making my first steps with Python/Django and wrote an example application with multiple Django apps in one Django project. Now I added another app called "dashboard" where Id like to displ…

Can I use a machine learning model as the objective function in an optimization problem?

I have a data set for which I use Sklearn Decision Tree regression machine learning package to build a model for prediction purposes. Subsequently, I am trying to utilize scipy.optimize package to solv…

How to store data like Freebase does?

I admit that this is basically a duplicate question of Use freebase data on local server? but I need more detailed answers than have already been given thereIve fallen absolutely in love with Freebase…

Django-celery : Passing request Object to worker

How can i pass django request object to celery worker. When try to pass the request object it throws a Error Cant Pickle Input ObjectsIt seems that celery serialize any arguments passed to worker. I tr…

How to get ROC curve for decision tree?

I am trying to find ROC curve and AUROC curve for decision tree. My code was something likeclf.fit(x,y) y_score = clf.fit(x,y).decision_function(test[col]) pred = clf.predict_proba(test[col]) print(skl…

pandas - stacked bar chart with timeseries data

Im trying to create a stacked bar chart in pandas using time series data:DATE TYPE VOL0 2010-01-01 Heavy 932.6129031 2010-01-01 Light 370.6129032 2010-01-01 Medium 569.4516133 …