Reputation: 3
The format which I'm using to execute some code based on which class the variable 'tester' is appears not to be working. How can I write the code such that the variable 'var' in the class 'testClass()' is changed .
I have tried changing the format from "if tester == testClass():" to "if testClass() in [tester]:", but neither work nor return errors. Changing 'var = second' to 'var = "second"' doesn't appear to help either, and neither does removing any brackets.
The code is as follows:
class fillClass():
fill = True
class testClass():
var = "first"
filler = True
tester = testClass()
oldVar = tester.var
print(oldVar,"is older variable")
second = "second"
if tester == testClass():
class testClass():
var = second
filler = True
tester = testClass()
newVar = tester.var
print(newVar,"is newer variable")
I would expect the output
first is older variable
second is newer variable
>>>
but the actual output is
first is older variable
first is newer variable
>>>
How can I fix this issue?
Many thanks!
Upvotes: 0
Views: 37
Reputation: 630
You are comparing an instance of a class with a class which will not work. I don't know if this is what you want to check but if yes you should do like this:
Instead of:
if tester == testClass():
You have to use:
if isistance(tester, testClass()):
Also, in your code, you have never used the fillClass
.
I am guessing that you want something like this:
class TestClass():
var = "first"
filler = True
tester = TestClass()
oldVar = tester.var
print(oldVar, "is older variable")
second = "second"
if tester.var == "first":
tester.var = second
newVar = tester.var
print(newVar, "is newer variable")
Please note that you should respect Python class name convention(capitalize camelcase) and you don't have to redefine your class again.
You should also know the difference between instance variables and class variables and you may want to use de class constructor:
class TestClass():
def __init__(self, var, filler=True):
self.var = var
self.filler = filler
Upvotes: 0
Reputation: 2062
The problem lies with this if-clause: if tester == testClass()
, which will always evaluate to false, since calling testClass()
instantiates a completely new object of type testClass. You want to check of what instance a variable is by using the function isinstance()
.
This is what you want:
class fillClass():
fill = True
class testClass():
var = "first"
filler = True
tester = testClass()
oldVar = tester.var
print(oldVar,"is older variable")
second = "second"
if isinstance(tester,testClass):
class testClass():
var = second
filler = True
tester = testClass()
newVar = tester.var
print(newVar,"is newer variable")
Upvotes: 1