I have the following snippet of code:
Employees1 = []
Emp_ID1 = 100
class Employee:
ID = None
FirstName = None
LastName = None
Salary = None
def __init__ (self, fn, ln, sal):
global Emp_ID1
Emp_ID1 += 1 # What's this?
self.ID = Emp_ID1
self.FirstName = fn
self.LastName = ln
self.Salary = sal
Employees1.append(self)
My question here is: what is the scope of the Employees1
list? I see it's defined outside function but it runs fine. So is Python treating this as a global variable? So we don't have to mention the keyword global
before a variable?
If I go by this assumption, then I have this snippet again:
value_789 = 0
class Self_Assign():
def assign():
value_789 += 1
print(value_789)
def assign():
value_789 += 1
print(value_789)
When I run this, it says local variable value_789 referenced beore assignment
. Why is it saying so? Why isn't it taking this as a global variable and running fine like before?
Also, when I run this code snippet like
obj = Self_Assign()
print(obj.assign)
I cannot see any print
done, it treats this assign as a method and says <bound method Self_Assign.assign of <__main__.Self_Assign object at 0x7fca74fed160>>
.
I do have a function assign()
defined outside class. How does Python differentiate between a method and a function? When I try to run the method assign using assign()
it says the same error local variable referenced...
.
If Python treats value_789
as a global variable it should've understood it like what it did with the Employee1 list
.
I read the article What's the difference between a method and a function? but still feel confused about how Python accesses a method and a function. What is the key difference between a method and a function? I have programmed in Java as well which too is OOP but is there any method concept there? All that we do are to define our own functions or use the inbuilt ones.