Hi I have staring programming with c and I conld'nt understand value scope in python.
here is my code
class ScenarioEnvironment():
def __init__(self):
print(self)
class report():
config = ScenarioEnvironment()
def __init__(self):
self.config = ScenarioEnvironment()
what happens passing config and config at init()?
and I wonder the value scope which config will be class valuable?
You need to know the differences between class attribute and instance object attribute.
Maybe these codes will help you:
class TestConfig1(object):
config = 1
def __init__(self):
self.config = 2
class TestConfig2(object):
config = 1
def __init__(self):
self.config2 = 2
if __name__ == "__main__":
print TestConfig1.config
t = TestConfig1()
print t.config
t2 = TestConfig2()
print t2.config
print t2.config2
more you can see the python blog.click here
Since your question seems a bit ambiguous, I'll just comment/fix your code:
class ScenarioEnvironment():
def __init__(self,x):
self.x = x # Assigning instance variable x to constructor parameter x.
print(self) # You're printing the object instance.
class report():
# Static variable shared amongst all classes.
config = ScenarioEnvironment(None) # Assigned to new instance of ScenarioEnvironment.
def __init__(self):
# No argument, must pass one (None).
# self.config is to a new ScenarioEnvironment instance.
self.config = ScenarioEnvironment(None)
Lets try out the classes.
Output:
s = ScenarioEnvironment(None)
r = report()
>>> <__main__.ScenarioEnvironment instance at 0x026F4238>
>>> <__main__.ScenarioEnvironment instance at 0x026F4300>
>>> <__main__.ScenarioEnvironment instance at 0x026F4350>
Related
In the __init__ function of a class I initialize some variables in order to make them available throughout my class and other classes.
These variables are given a value at a later stage in a function of a different class. But whenever they are set their identity changes. Since I have been passing around the references to these variables I don't want their identity to change.
I have already tried copy.copy() and copy.deepcopy(), but this also changes the identity of the variables.
The code below describes the situation in a simple way:
class MyObject:
def __init__(self):
self.name = 'test_object'
def set_name(self, name):
self.name = name
class MyClass:
def __init__(self):
self.my_object = MyObject()
def create_object():
new_object = MyObject()
new_object.set_name('new_object')
print(f'Address of new object in function: {id(new_object)}')
return new_object
if __name__ == '__main__':
my_class = MyClass()
print(f'Identity when variable has only be initialized: {id(my_class.my_object)}')
my_class.my_object = create_object()
print(f'Identity after the create has been called: {id(my_class.my_object)}')
The code above produces the following output:
Identity when variable has only be initialized: 87379952
Address of new object in function: 87425104
Identity after the create has been called: 87425104
What I would like to have is that the identity of my_class.my_object stays the same and does not change to the identity of the object created in the function. Would someone know how to achieve this?
Instead of creating a new instance of MyObject when initializing an instance of MyClass, you can explicitly pass a reference to an existing MyObject instance:
class MyObject:
def __init__(self):
self.name = 'test_object'
def set_name(self, name):
self.name = name
class MyClass:
def __init__(self, my_object):
self.my_object = my_object
def create_object():
new_object = MyObject()
new_object.set_name('new_object')
print('Address of new object in function:', id(new_object))
return new_object
if __name__ == '__main__':
my_object = create_object()
print('Identity after the create has been called:', id(my_object))
my_class = MyClass(my_object)
print('Identity when my_class has been initialized:', id(my_class.my_object))
Output:
Address of new object in function: 140518937186936
Identity after the create has been called: 140518937186936
Identity when my_class has been initialized: 140518937186936
I have a question regarding the classes in python3. In my programm i have a "main" class that is getting started first and sets some parameters that are needed for the other parts of the programm. But now my other classes need some objects of the main class. How can i use the objects of the main class without initialising the main class everytime the subclass needs the object ? I looked into python inheritance but maybe i didnt understand it correctly
class Chunk(main.Main):
def __init__(self,pos_in_world_x,pos_in_world_y):
#self.chunksize = settings.blocks_per_chunk
self.prog = main.Main.prog
self.ctx = main.Main.ctx
this is my code for the subclass
You can use class variables:
class Main():
prog = 1
ctx = 2
def __init__(self):
pass
class Chunk(Main):
def __init__(self, pos_in_world_x, pos_in_world_y):
self.prog = Main.prog
self.ctx = Main.ctx
a = Chunk(3, 4)
print(a.prog) # 1
print(a.ctx) # 2
If you can't change Main to move your definitions outside __init__, then what you're asking for is impossible. If your variable is defined in __init__, you can't access it before calling __init__, i.e. initialising the class. You can't get round this.
You need a super __init__ call in your subclass and if you have that you only need to do:
class Chunk(main.Main):
def __init__(self,pos_in_world_x,pos_in_world_y):
super().__init__()
#self.chunksize = settings.blocks_per_chunk
Both of the assignments are done by Main's __init__.
But I think that Chunk has not an is-a but rather a has-a relation with Main so Main should actually be an argument rather than a super class:
class Chunk(object):
def __init__(self, main, pos_in_world_x,pos_in_world_y):
#self.chunksize = settings.blocks_per_chunk
self.prog = main.prog
self.ctx = main.ctx
Any one that creates a Chunk must pass a Main instance.
It is actually difficult to hide information in Python, so here are a few options which don't require inheritance (see jpp's answer for the inheritance option). In general, the code is easier to understand when you pass information explicitly (option 1 below, or inheritance), but there may be cases where you'd prefer the other options.
Option 1: The needed info can simply be passed as additional arguments to Chunk's __init__ (either by passing the prog and ctx values themselves, or by passing the Main class or its instance - depending on whether the needed info is stored as class or instance variables). Here's an example of passing Main as an argument:
class Main():
prog = 1
ctx = 2
def __init__(self):
pass
class Chunk():
def __init__(self, pos_in_world_x, pos_in_world_y, M):
#self.chunksize = settings.blocks_per_chunk
self.prog = M.prog
self.ctx = M.ctx
c = Chunk(3, 4, Main)
print(c.prog) # 1
print(c.ctx) # 2
Option 2: Chunk can access Main's class variables directly:
class Main():
prog = 1
ctx = 2
def __init__(self):
pass
class Chunk():
def __init__(self, pos_in_world_x, pos_in_world_y):
#self.chunksize = settings.blocks_per_chunk
self.prog = Main.prog
self.ctx = Main.ctx
c = Chunk(3, 4)
print(c.prog) # 1
print(c.ctx) # 2
Option 3: Chunk can access the instance variables of the Main instance directly (Main needs to be instantiated before Chunk is instantiated):
class Main():
def __init__(self):
self.prog = 1
self.ctx = 2
class Chunk():
def __init__(self, pos_in_world_x, pos_in_world_y):
#self.chunksize = settings.blocks_per_chunk
self.prog = m.prog
self.ctx = m.ctx
m = Main()
c = Chunk(3, 4)
print(c.prog) # 1
print(c.ctx) # 2
I am new to python.
Base class/python file(Base.py).
SESSION_ID = ""
def m1():
print "SESSION_ID in base: ",SESSION_ID
Derived class(Derived.py)
from Base import *
class Derived():
def m2(self):
global SESSION_ID
SESSION_ID = 10
print "SESSION_ID in derived: ", SESSION_ID
def main():
c2 = Derived()
c2.m2()
m1()
if __name__ == "__main__":
main()
When I execute Derived.py file below is the output:
SESSION_ID in derived: 10
SESSION_ID in base:
I want the value which is set in m2() to be reflected in m1(). So the expected output is:
SESSION_ID in derived: 10
SESSION_ID in base: 10
Can you please help?
The global variable in a module is merely an attribute (i.e. a member
entity) of that module.
As result of that when you use import *, the new local module global SESSION_ID is created, so the SESSION_ID in the base is immune to the changes you are doing in the Derived.
Basically, modifying base.SESSION_ID don't require usage of the global statement in the Derived.py, adjusting import is enough, see code below:
from settings import base
class Derived():
def m2(self):
base.SESSION_ID = 10
print "SESSION_ID in derived: ", base.SESSION_ID
def main():
c2 = Derived()
c2.m2()
base.m1()
if __name__ == "__main__":
main()
Your Derived class is not derived from anything inside Base.py. Here, you are just calling a basic function from Base from within Derived, nothing more.
Here is an example on class inheritance in Python3 :
>>> class Base():
>>> SESSION = 42
>>>
>>> def print_session(self):
>>> print("Base session : %d" % self.SESSION)
>>>
>>> class Derived(Base):
>>> SESSION = 999
>>>
>>> d = Derived()
>>> d.print_session()
Base session : 999
I would avoid using global and class-scoped variables if at all possible. These can make your program harder to understand (if something else changes a global underneath you it's hard to notice) and test (you need to reset all global state between every test; it's often easier to just create new empty state).
I might restructure this example by creating a state object:
class State:
def __init__(self):
self.session_id = ''
And then making that explicitly be a property, say, of the base class:
class Base:
def __init__(self, state):
self.state = state
def m1(self):
print("SESSION_ID in base: " + str(self.state.session_id))
class Derived(Base):
def m2(self):
self.state.session_id = '10'
print("SESSION_ID in derived: " + str(self.state.session_id))
Then in your main function you need to explicitly create the state object and pass it in
def main():
state = State()
c2 = Derived(state)
c2.m2()
c2.m1()
But, critically, your tests don't need to worry about state leakage
def test_m2():
state = State()
obj = Derived(state)
obj.m2()
assert state.session_id == '10'
def test_m1():
state = State()
obj = Base(state)
obj.m1()
# If the session ID was a global or a class variable,
# you'd get a different result if m2() was called or not
assert state.session_id == ''
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class? I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!
class Test:
def __init__(self):
self.root = None
running_sum = 0
def test_function(self):
print(Test.running_sum)
return
x = Test()
x.test_function()
Error:
Traceback (most recent call last):
File "so.py", line 1, in <module>
class Test:
File "so.py", line 10, in Test
x = Test()
NameError: name 'Test' is not defined
Use self parameter provided in the method signature.
Note that what you wrote is not a method, but an external function using class Test. To write a method of Test, the def should be at one level of indentation inside class Test as following:
class Test:
def __init__(self):
self.running_sum = 0
def test_function(self):
print(self.running_sum)
There are several things to add if you want an explanation behind this "best practice".
Assuming you write the following code:
class Test:
numbers = []
def add(self, value):
self.numbers.append(value)
The Test.numbers list is instantiated once and shared accross all instances of Test. Therefore, if 2 different instances add to the list, both act on the same list:
a = Test()
b = Test()
a.add(5)
b.add(10)
assert a.numbers == b.numbers == Test.numbers
When creating instance variables in the __init__ function, __init__ will be run at each instantiation, and therefore, the list will no longer be shared because they will be created for each individual instances.
class Test:
def __init__(self):
self.numbers = []
def add(self, number):
self.numbers.append(number)
a = Test()
b = Test()
a.add(5)
b.add(10)
assert a != b
As an object attribute: each object gets its own.
Test is the class; self is the Test object that invoked the method.
class Test:
def __init__(self):
self.root = None
self.running_sum = 0
def test_function(self):
self.running_sum += 1
print(self.running_sum)
return
x = Test()
y = Test()
x.test_function()
y.test_function()
Output:
1
1
As a class attribute: all objects share the same variable.
self.__class__ is the class of the invoking object (i.e. Test).
class Test:
running_sum = 0
def __init__(self):
self.root = None
def test_function(self):
self.__class__.running_sum += 1
print(self.__class__.running_sum)
return
x = Test()
y = Test()
x.test_function()
y.test_function()
Output:
1
2
how do I reference this variable across other functions in the class
Several things I see wrong here. First of all, you are calling running_sum on the class itself which doesn't make sense since you are declaring running_sum as an attribute of an instance of Test. Second, from the way you formatted your question, it seems that test_function is outside of the class Test which doesn't make sense since you are passing self to it, implying it is an instance method. To resolve you could do this:
class Test:
def __init__(self):
self.running_sum = 0
def test_function(self):
print(self.running_sum)
Then again this also is weird... Why would you need a "test_function" when you can simply test the value of running_sum by simply doing:
x = Test()
x.running_sum
In your __init__ function, you've created a local variable. That variable will no longer exist after the function has completed.
If you want to create a variable specific to the object x then you should create a self.running_sum variable
class Test:
def __init__(self):
self.root = None
self.running_sum = 0
def test_function(self):
print(self.running_sum)
If you want to create a variable specific to the class Test then you should create a Test.running_sum variable.
class Test:
running_sum = 0
def __init__(self):
self.root = None
def test_function(self):
print(Test.running_sum)
I'm new to Python - and just trying to better understand the logic behind certain things.
Why would I write this way (default variables are in __init__):
class Dawg:
def __init__(self):
self.previousWord = ""
self.root = DawgNode()
self.uncheckedNodes = []
self.minimizedNodes = {}
def insert( self, word ):
#...
def finish( self ):
#...
Instead of this:
class Dawg:
previousWord = ""
root = DawgNode()
uncheckedNodes = []
minimizedNodes = {}
def insert( self, word ):
#...
def finish( self ):
#...
I mean - why do I need to use __init__ -> if I can just as easily add default variables to a class directly?
When you create variables in the Class, then they are Class variables (They are common to all the objects of the class), when you initialize the variables in __init__ with self.variable_name = value then they are created per instance and called instance variables.
For example,
class TestClass(object):
variable = 1
var_1, var_2 = TestClass(), TestClass()
print var_1.variable is var_2.variable
# True
print TestClass.variable is var_1.variable
# True
Since variable is a class variable, the is operator evaluates to True. But, in case of instance variables,
class TestClass(object):
def __init__(self, value):
self.variable = value
var_1, var_2 = TestClass(1), TestClass(2)
print var_1.variable is var_2.variable
# False
print TestClass.variable is var_1.variable
# AttributeError: type object 'TestClass' has no attribute 'variable'
And you cannot access an instance variable, with just the class name.
When you write this:
class Dawg:
previousWord = ""
root = DawgNode()
uncheckedNodes = []
minimizedNodes = {}
Those are not instance variables, they're class variables (meaning: the same variables with the same values are shared between all instances of the class.) On the other hand, this:
class Dawg:
def __init__(self):
self.previousWord = ""
self.root = DawgNode()
self.uncheckedNodes = []
self.minimizedNodes = {}
... Is declaring instance variables, meaning: the values are different for each instance of the class. As you see, each snippet means a completely different thing, and you have to pick the one that is appropriate for you. Hint: most of the time you're interested in instance variables, because class variables define a kind of shared global state for your objects, which is error prone.