Python and Variable Scope

2024/11/15 10:07:05

So I am recently new to Python, but I seem to be able to program some stuff and get it working. However I've been trying to expand my knowledge of how things work in the language, and putting this simple file together confuses me.

class TestA:def __init__(self):self.varNum = 3def printNum(self):print(self.varNum)class TestB:varNum = 0def __init__(self):varNum = 3def printNum(self):global varNumprint(varNum)a = TestA()
a.printNum()b = TestB()
b.printNum()

The code to TestA prints 3 to the screen properly. However the code for TestB instead gives me a NameError stating that: 'varNum' is not defined. And I get that error whether i have the global varNum line there or not.

I suppose what confuses me, is I see the __init__ function as a class constructor. And when I have programmed with languages such as Java or C# I've declared global variables outside of the constructor so that their scope is the whole class. Is that not a thing in Python? The code I've written I just kind of tagged self. onto everything because I was just trying to get some stuff put together quickly, but I am trying to figure more out about the language now. Is self. the only way in Python to make class scope variables? Or are there other ways?

Thanks for your time :)

Answer

In Python, variables declared inside the class definition, but not inside a method are class or static variables:

class TestB:varNum = 0

This creates a class-level varNum variable, but this is distinct from any instance-level varNum variable, so you could have:

class TestB:varNum = 0def __init__(self):self.varNum = 3b = TestB()
print(b.varNum)  # print 3
print(TestB.varNum)  # print 0

Thus, class TestB should work in this way:

class TestB:varNum = 0def __init__(self):self.varNum = 3def printInstanceNum(self):print(self.varNum)    def printClassNum():print(TestB.varNum)b = TestB()
b.printInstanceNum()  # print 3
TestB.printClassNum()  # print 0

Note that since there's no any reference to instance object in method printClassNum(), we don't have to put self as an argument. The method could actually become a staticmethod:

class TestB:varNum = 0    @staticmethoddef printClassNum():print(TestB.varNum)

Ref

  • class objects
  • static method
https://en.xdnf.cn/q/119327.html

Related Q&A

How to check if element is orthogonally adjacent (next to) to existing elements?

Im trying to make a simple game where a building placed in a nested list must be next to another building. The problem I face is that if the building was placed at the sides, I cant use for loops to ch…

How to add new column(header) to a csv file from command line arguments

The output of the following code:-import datetime import csv file_name=sample.txt with open(file_name,rb) as f: reader = csv.reader(f,delimiter=",") …

Pattern matching and replacing in Python

Im trying to take a string that can be anything like "Hello here is a [URL]www.url.com[/URL] and its great." and be able to extract whatever is between [URL] and [/URL] and then modify the st…

In Python word search, searching diagonally, printing result of where word starts and ends

I have a friend of mine tutoring me in learning Python and he gave me this project where a user will read a word search into the program and the file includes a list of words that will be in the word s…

Selenium python : element not interactable

I am trying to scrape information from this website example website I need to get the version 2021 and search by code. Here is my code: from selenium import webdriver from selenium.webdriver.chrome.opt…

Date into matplotlib graph

How can I use a date from a Sqlite database on the x-axis to make a bar graph with matplotlib?If I convert the date to unix timestamp the graph works, but I would like to get something like this: http…

Non blocking IO - Programming model

In non blocking IO programming model, a thread blocked on data available channels, as shown below, in python,while True:readers, _, _ = select.select([sys.stdin, sock], [], []) # blocked select()for re…

How to globally change xticks label relplot in Seaborn

I am facing an issue to globally changed the x-tick label for plot render using the relplot The idea was to change the int to string x-tick label for both plot. The desired label is [a,b,c,d] However, …

How to solve MatplotlibDeprecationWarning: scipy.stats.norm.pdf warning?

I am using matplotlib in my Python code. I got following warning: xxx.py:88: MatplotlibDeprecationWarning: scipy.stats.norm.pdfy = 100 * mlab.normpdf(bin_middles, mu, sigma)*bin_width I was wondering…

time data 42:53.700 does not match format %H:%M:%S.%f (match)

I am trying to convert a column in string format to DateTime format, However, I am getting the following error, could somebody please help? The error:time data 42:53.700 does not match format %H:%M:%S…