Python Variable Scope and Classes

2024/10/13 7:25:51

In Python, if I define a variable:

my_var = (1,2,3)

and try to access it in __init__ function of a class:

class MyClass:def __init__(self):print my_var

I can access it and print my_var without stating (global my_var).

If I put my_var right after class MyClass however, I get scope error (no global variable found).

What is the reason for this? How should I do this? Where can I read about this to learn? I did read Python Class page but I did not encounter its explanation.

Thank you

Answer

Complementing @mgilson's answer: Note that Python Class variables are shared among the class instances. And the behaviour might be VERY unexpected and seem weird. In practice it works like this:

class MyClass(object):my_var = 10def __init__(self):print(self.my_var)m1 = MyClass()
print(m1.my_var)
>>> 10          # this is fineMyClass.my_var = 20
print(m1.my_var)
>>> 20          # WTF? :) --> shared valuem2 = MyClass()
print(m2.my_var)
>>> 20          # this is expectedm1.my_var = 30
print(MyClass.my_var)
>>> 20          # this is also expectedMyClass.my_var = 40 
print(m1.my_var)
>>> 30           # But WHY? Isn't it shared? --> # The value WAS shared until m1.my_var = 30 has happened.print(m2.my_var)
>>> 40           # yep m2.my_var's value is still shared :)
https://en.xdnf.cn/q/69558.html

Related Q&A

How to check if valid excel file in python xlrd library

Is there any way with xlrd library to check if the file you use is a valid excel file? I know theres other libraries to check headers of files and I could use file extension check. But for the sake of…

ValueError: Invalid file path or buffer object type: class tkinter.StringVar

Here is a simplified version of some code that I have. In the first frame, the user selects a csv file using tk.filedialog and it is meant to be plotted on the same frame on the canvas. There is also a…

Is there a way to reopen a socket?

I create many "short-term" sockets in some code that look like that :nb=1000 for i in range(nb):sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sck.connect((adr, prt)sck.send(question …

How django handles simultaneous requests with concurrency over global variables?

I have a django instance hosted via apache/mod_wsgi. I use pre_save and post_save signals to store the values before and after save for later comparisons. For that I use global variables to store the p…

Why cant I string.print()?

My understanding of the print() in both Python and Ruby (and other languages) is that it is a method on a string (or other types). Because it is so commonly used the syntax:print "hi"works.S…

Difference between R.scale() and sklearn.preprocessing.scale()

I am currently moving my data analysis from R to Python. When scaling a dataset in R i would use R.scale(), which in my understanding would do the following: (x-mean(x))/sd(x)To replace that function I…

Generate random timeseries data with dates

I am trying to generate random data(integers) with dates so that I can practice pandas data analytics commands on it and plot time series graphs. temp depth acceleration 2019-01-1 -0.218062 -1.21…

Spark select top values in RDD

The original dataset is:# (numbersofrating,title,avg_rating) newRDD =[(3,monster,4),(4,minions 3D,5),....] I want to select top N avg_ratings in newRDD.I use the following code,it has an error.selectne…

Python module BeautifulSoup extracting anchors href

i am using BeautifulSoup module to select all href from html by this way:def extract_links(html):soup = BeautifulSoup(html)anchors = soup.findAll(a)print anchorslinks = []for a in anchors:links.append(…

Pandas: how to get a particular group after groupby? [duplicate]

This question already has answers here:How to access subdataframes of pandas groupby by key(6 answers)Closed 9 years ago.I want to group a dataframe by a column, called A, and inspect a particular grou…