Lets say i have the following code:
class asd:
def __init__(self):
self.var = "default"
def changeagain():
xa = asd()
xa.var = "changed"
return xa
def change(objct:asd):
newobjc = changeagain()
objct = newobjc
print(objct.var)
test = asd()
change(test)
print(test.var)
what i expect as output is:
changed
changed
nonetheless i get:
changed
default
What is the problem?
What i must do to get the desired output?
Here, you are changing the value of an object's instance variable and expecting the change to b reflected in another object. Whereas it is not possible in the case of instance variables of objects.
As per your need, I've changed certain statements in your program :
class asd:
var = "default"
def changeagain():
xa = asd()
asd.var = "changed"
return xa
def change(objct:asd):
newobjc = changeagain()
objct = newobjc
print(objct.var)
test = asd()
change(test)
print(test.var)
class asd:
def __init__(self):
self.var = "default"
def changeagain(asd):
# xa = asd()
asd.var = "changed"
return asd
def change(asd):
newobjc = changeagain(asd)
objct = newobjc
print(objct.var)
test = asd()
change(test)
print(test.var)
I have commented out the object creation in the changeagain() and passed the object of the class for which you want to change the value.
Earlier you were passing an object of the class but changing the value for a different object.
Happy coding
Related
I am writing a class where I would like to pass function as a class attribute and later use it, like that:
class Nevronska_mreza:
def __init__(self, st_vhodni, st_skriti, st_izhod, prenosna_funkcija=pf.sigmoid):
self.mreza = []
self.st_vhodni = st_vhodni
self.st_skriti = st_skriti
self.st_izhodni = st_izhod
self.prenosna_funckija = prenosna_funkcija
self.mreza.append([{'utezi': [random() for i in range(st_vhodni + 1)]} for j in range(st_skriti)])
self.mreza.append([{'utezi': [random() for i in range(st_skriti + 1)]} for j in range(st_izhod)])
def razsirjanje_naprej(self, vhod):
for sloj in self.mreza:
nov_vhod = []
for nevron in sloj:
nevron['izhod'] = self.prenosna_funkcija(self.aktivacijska_funkcija(nevron['utezi'], vhod))
nov_vhod.append(nevron['izhod'])
vhod = nov_vhod
return vhod
but it seems like this isn't the right way, I get the following error:
AttributeError: 'Nevronska_mreza' object has no attribute 'prenosna_funkcija'
Is it possible to do something like that?
Yes you can pass a function around as an argument however you have made a couple of mistakes.
Firstly you have used the word function, although not a reserved word it should be avoided as a name of an entity such as a variable.
Secordly you have used an optional parameter before mandatory parameters which will cause an error such as:
File "test.py", line 5
def __init__(self, function=fun1, data1, data2):
^
SyntaxError: non-default argument follows default argument
Thirdly when calling the method you have not specified the scope, the function name is in the self scope of the object.
Taking all of these into account the following is working code
def fun1(x):
return x+1
class A:
def __init__(self, data1, data2, fn=fun1):
self.fn = fn
self.data1 = data1
self.data2 = data2
def some_method(self):
y = self.fn(self.data1)
print(y)
b = A(1, 2, fun1)
b.some_method()
After posting your full code I can see that you currently have self.prenosna_funckija instead of prenosna_funkcija in the following line:
self.prenosna_funckija = prenosna_funkcija
This would explain the attribute error as when you are calling self.prenosna_funkcija it genuinely does not exist.
You're close:
def fun1(x):
return x+1
class A:
def __init__(self, function=fun1, data1=None, data2=None):
self.function = function
self.data1 = data1
self.data2 = data2
def some_method(self):
y = self.function(self.data1)
return y
a = A(data1 = 41)
result = a.some_method()
print(result)
prints
42
I have the following class and I want the instance variable api_id_bytes to update.
class ExampleClass:
def __init__(self):
self.api_key = ""
self.api_id = ""
self.api_id_bytes = self.api_key.encode('utf-8')
I'd like to be able to have this outcome:
>>>conn = ExampleClass()
>>>conn.api_key = "123"
>>>conn.api_id = "abc"
>>>print(conn.api_id_bytes)
b'123'
>>>
I basically need the self.api_key.encode('utf-8') to run when an api_id is entered but it doesn't, it only does through the initial conn = ExampleClass().
I'm not sure what this is called so searching didn't find an answer.
Here's how you could do it by making api_id_bytes a property.
class ExampleClass:
def __init__(self):
self.api_key = ""
self.api_id = ""
#property
def api_id_bytes(self):
return self.api_key.encode('utf-8')
Now conn.api_id_bytes will always be correct for the current value of conn.api_key.
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!
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")
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
I am trying to add new objects to a class(emne) but the new instances of the class needs to be created using user input. So i need a way to be able to chose the name for the object and set some of the values of the objects with user input.
I have already tried to create a function that passes the value of the user input into a x = emner(x) to create it but it only returns:
AttributeError: 'str' object has no attribute 'fagKode'
so i think my issue is that the value of the input is created as a string so that it is not understood as a way to create the function
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne():
nyttEmne = input("test:")
nyttEmne=Emne(nyttEmne)
expected result is that the code creates a new instance of the class.
If by choosing a name you mean your fagKode attribute, what you need is:
fagKode = input('Enter code: ')
Emne(fagKode)
You're adding the instances of Enme to the list in the constructor, so you don't need to save them to a variable.
Alternatively, you can handle that in the function:
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
def leggTilEmne():
nyttEmne = input("test:")
enme.append(Emne(nyttEmne))
I'm not sure what exactly you are asking, since you haven't responded to the comments. So,
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne(self, value): # <--- is this what you want
self.nyttEmne= Emne(value)
This is an example of when to use a class method. __init__ should not be appending to a global variable, though. Either 1) have the class method append to a class attribute, or 2) have it return the object and let the caller maintain a global list.
emne = []
class Emne:
emne = []
def __init__(self, fag_kode):
self.fag_kode = fag_kode
self.karakter = ""
#classmethod
def legg_til_emne_1(cls):
nytt_emne = input("test:")
cls.emne.append(cls(nytt_emne))
#classmethod
def legg_til_emne_2(cls):
nyttEmne = input("test:")
return cls(nyttEmne)
Emne.legg_til_emne_1() # Add to Emne.emne
e = Emne.legg_til_emne_2()
emne.append(e)
Bellow is my current code, I am pretty new to Python. I am trying to create a list of Photo instances, where each Photo instance uses the data from each tuple in the tups_list. and save that list in a variable photo_insts. Currently I am not receiving an error, literally, nothing is happening in terminal when I try to run the file.
photo_insts = []
tups_list = [("Portrait 2","Gordon Parks",["chicago", "society"]),("Children in School","Dorothea Lange",["children","school","1930s"]),("Airplanes","Margaret Bourke-White",["war","sky","landscape"])]
class Photo2(object):
def __init__(self, title_str, photo_by,tags_list):
self.title = title_str
self.artist = photo_by
self.tags = tags_list
for i in tups_list:
photo_tuple = (i[0],i[1],i[2])
photo_insts.append(photo_tuple)
print i
Below are tests to run to check for diffrent values:
class Phototest(unittest.TestCase):
def test_photo_insts1(self):
self.assertEqual(type(photo_insts),type([]))
def test_photo_insts2(self):
self.assertEqual(type(photo_insts[0]),type(Photo("Photo2","Photo Student",["multiple","tags"])))
def test_photo_insts3(self):
self.assertEqual([x.title for x in photo_insts],["Portrait 2", "Children in School", "Airplanes"])
def test_photo_insts4(self):
self.assertEqual([x.artist for x in photo_insts],["Gordon Parks","Dorothea Lange","Margaret Bourke-White"])
def test_photo_insts5(self):
self.assertEqual([x.tags for x in photo_insts],[["chicago","society"],["children", "school","1930s"],["war","sky","landscape"]])
I guess this is a typo:
photo_tuple = (i[0],i[1],i[2])
=>
photo_tuple = Photo2 (i[0],i[1],i[2])
Function __init__ is called on creation of an instance Photo2.
If you call Photo2 () within the function __init__ then you get a recursion !
=> The code should look like :
class Photo2(object):
def __init__(self, title_str, photo_by, tags_list):
self.title = title_str
self.artist = photo_by
self.tags = tags_list
# end class
tups_list = [
("Portrait 2","Gordon Parks",["chicago", "society"])
,("Children in School","Dorothea Lange",["children","school","1930s"])
,("Airplanes","Margaret Bourke-White",["war","sky","landscape"])
]
photo_insts = []
for i in tups_list :
photo_tuple = Photo2 (i[0],i[1],i[2])
photo_insts.append(photo_tuple)
print i[0]
for p in photo_insts :
print repr (p)
Output in console :
Portrait 2
Children in School
Airplanes
<__main__.Photo2 object at 0xb7082cac>
<__main__.Photo2 object at 0xb7082ccc>
<__main__.Photo2 object at 0xb7082cec>