I have my code setup this way:
class Test():
def __init__(self):
self.offset = [0,0]
#property
def offset(self):
return self._offset
#offset.setter
def offset(self,offset):
print("set")
self._offset = offset
test = Test()
test.offset[1] -= 1
but the setter is being called only once even though I am changing my variable twice, anyone is able to help ?
test.offset[1] -= 1
This line of your code is calling the getter not the setter. You get the list from the test object and then you alter its contents.
Same as if you wrote:
v = test.offset # get the list
v[1] -= 1 # alter the contents of the list
I have a class Foo with its instances having a "balance" attribute. I'm designing it in such a way that Foo can track all the balances of its active instances. By active I mean instances that are currently assigned to a declared variable, of part of a List that is a declared variable.
a = Foo(50) # Track this
b = [ Foo(20) for _ in range(5) ] # Track this
Foo(20) # Not assigned to any variable. Do not track this.
Another feature of Foo is that is has an overloaded "add" operator, where you can add two Foo's balances together or add to a Foo's balance by adding it with an int or float.
Example:
x = Foo(200)
x = x + 50
y = x + Foo(30)
Here is my code so far:
from typing import List
class Foo:
foo_active_instances: List = []
def __init__(self, balance: float = 0):
Foo.foo_active_instances.append(self)
self.local_balance: float = balance
#property
def balance(self):
"""
The balance of only this instance.
"""
return self.local_balance
def __add__(self, addend):
"""
Overloading the add operator
so we can add Foo instances together.
We can also add more to a Foo's balance
by just passing a float/int
"""
if isinstance(addend, Foo):
return Foo(self.local_balance + addend.local_balance)
elif isinstance(addend, float | int):
return Foo(self.local_balance + addend)
#classmethod
#property
def global_balance(cls):
"""
Sum up balance of all active Foo instances.
"""
return sum([instance.balance for instance in Foo.foo_active_instances])
But my code has several issues. One problem is when I try to add a balance to an already existing instance, like:
x = Foo(200)
x = x + 50 # Problem: This instantiates another Foo with 200 balance.
y = Foo(100)
# Expected result is 350, because 250 + 100 = 350.
# Result is 550
# even though we just added 50 to x.
print(Foo.global_balance)
Another problem is replacing a Foo instance with None doesn't remove it from Foo.foo_active_instances.
k = Foo(125)
k = None
# Expected global balance is 0,
# but the balance of the now non-existing Foo still persists
# So result is 125.
print(Foo.global_balance)
I tried to make an internal method that loops through foo_active_instances and counts how many references an instance has. The method then pops the instance from foo_active_instance if it doesn't have enough. This is very inefficient because it's a loop and it's called each time a Foo instance is made and when the add operator is used.
How do I rethink my approach? Is there a design pattern just for this problem? I'm all out of ideas.
The weakref module is perfect for this design pattern. Instead of making foo_active_instances a list, you can make it a weakref.WeakSet. This way, when a Foo object's reference count falls to zero (e.g., because it wasn't bound to a variable), it will be automatically removed from the set.
class Foo:
foo_active_instances = weakref.WeakSet()
def __init__(self, balance: float = 0) -> None:
Foo.foo_active_instances.add(self)
...
In order to add Foo objects to a set, you'll have to make them hashable. Maybe something like
class Foo:
...
def __hash__(self) -> int:
return hash(self.local_balance)
You can use inspect to check if the __init__ or __add__ methods have been called as part of an assignment statement. Additionally, you can keep a default parameter in __init__ to prevent increasing your global sum by the value passed to it when creating a new Foo object from __add__:
import inspect, re
def from_assignment(frame):
return re.findall('[^\=]\=[^\=]', inspect.getframeinfo(frame).code_context[0])
class Foo:
global_balance = 0
def __init__(self, balance, block=False):
if not block and from_assignment(inspect.currentframe().f_back):
Foo.global_balance += balance
self.local_balance = balance
def __add__(self, obj):
if from_assignment(inspect.currentframe().f_back) and not hasattr(obj, 'local_balance'):
Foo.global_balance += obj
return Foo(getattr(obj, 'local_balance', obj), True)
a = Foo(50)
b = [Foo(20) for _ in range(5)]
Foo(20)
print(Foo.global_balance) #150
x = Foo(200)
x = x + 50
y = Foo(100)
print(Foo.global_balance) #350
I was kinda playing around with Object Oriented Programming in python and ran into an error i havent encountered before..:
class Main:
def __init__(self, a , b):
self.a = a
self.b = b
def even(self):
start = self.a
slut = self.b
while start <= slut:
if start % 2 == 0:
yield start
start += 1
def odd(self):
start = self.a
slut = self.b
while start <= slut:
if start % 2 != 0:
yield start
start += 1
def display():
evens = list(num.even())
odds = list(num.odd())
print(f"{evens}'\n'{odds}")
num = Main(20, 50)
Main.display()
Take a look at the last class method, where there shouldent be a 'self' as a parameter for the program to Work..Why is that? I thought every class method should include a 'self' as a parameter? The program wont work with it
There should be a self parameter, if it's intended to be an instance method, and you would get an error if you tried to use it as so, i.e., num.display().
However, you are calling it via the class, and Main.display simply returns the function itself, not an instance of method, so it works as-is.
Given that you use a specific instance of Main (namely, num) in the body, you should replace that with self:
def display(self):
evens = list(self.even())
odds = list(self.odd())
print(f"{evens}'\n'{odds}")
and invoke it with
num.display()
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 6 years ago.
The issue I appear to be having is that when I run a code that uses the plusMinusAverage class more than once (in my case a for loop), the new instance of the class keeps references to the previous list of pmaDicts created by the previous plustMinusAverage creation and adds to the end of it.
Meaning
(Code that results this is further down below)
things = []
for i in range(2):
thing[i] = plusMinusAverage(count3D=2)
print thing[i]
print thing[i].values3D
>>> (plusMinusAverage at 0x00NSTUFF1)
>>> [{"x":(attr.connection at 0x1234),"y":(attr.connection at 0x2345), etc..},
{"x":(attr.connection at 0x3456),"y":(attr.connection at 0x4567), etc..}]
>>> (plusMinusAverage at 0x00NSTUFF2)
>>> [{"x":(attr.connection at 0x1234),"y":(attr.connection at 0x2345), etc..},
{"x":(attr.connection at 0x3456),"y":(attr.connection at 0x4567), etc..},
{"x":(attr.connection at 0x5678),"y":(attr.connection at 0x6789), etc..},
{"x":(attr.connection at 0x7890),"y":(attr.connection at 0x8901), etc..}]
What gets me about this is that it appears to print out the object, but then the list appears to point to the original but with more entries. I don't get why the list would not be a unique one.
Sorry for the massive posting of code below, but I figured this issue has enough nuances that trying to make a simpler version would likely invite solutions that wouldn't work for my circumstance, and since I'm not certain where the issue lies exactly, I'm going to include all the pertinent parts where it might be going wrong.
..plus maybe someone who works in maya can use this to build their own shaderNode tools.
class Tracker2(object):
dag = ""
obj = ""
getTime = "current"
def setPathing(self):
if self.nodeName == None:
self.nodeName = cmds.createNode('transform')
cmds.addAttr(self.nodeName, sn="type", ln="type", dt="string")
cmds.setAttr(self.nodeName + ".type", type="string", keyable=0)
sel = om.MSelectionList()
sel.add(self.nodeName)
self.obj = om.MObject()
self.dag = om.MDagPath()
sel.getDependNode(0, self.obj)
try:
sel.getDagPath(0, self.dag)
except:
pass
def __init__(self):
if not self.dag and not self.obj:
self.setPathing()
def fullpath(self):
if self.dag and self.dag.fullPathName():
return self.dag.fullPathName()
return om.MFnDependencyNode(self.obj).name()
class shaderNode(Tracker2):
def __init__(self):
self.nodeName = cmds.shadingNode(self.type,au=1)
Tracker2.__init__(self)
class connection(object):
def __init__(self, attr, *args):
self.attr = attr
def __set__(self, instance, value):
if isinstance(value,basestring):
try:
cmds.connectAttr(value,instance.fullpath()+"."+self.attr,f=1)
except Exception as inst:
cmds.warning(inst)
elif not value:
temp = cmds.listConnections(instance.fullpath()+"."+self.attr,s=1,d=0)
if temp:
cmds.disconnectAttr(instance.fullpath()+"."+self.attr, temp[0])
else:
cmds.warning("Set Connection: Source attribute is non-string value | "+value)
def __get__(self, instance, owner):
tempIn = cmds.listConnections(instance.fullpath()+"."+self.attr,s=1,d=0)
tempIn = tempIn if tempIn else []
tempOut = cmds.listConnections(instance.fullpath()+"."+self.attr,s=0,d=1)
tempOut = tempOut if tempOut else []
#returns list of [[incoming] , [outgoing]]
return [tempIn,tempOut]
In separate py file where class containing connection is loaded as attr
class pmaDict(dict):
def __init__(self,instance,*args,**kwargs):
self.instance = instance
dict.__init__(self,*args,**kwargs)
def __getitem__(self, key):
thing = dict.__getitem__(self,key)
if key in self and isinstance(dict.__getitem__(self, key),attr.Attribute):
return thing.__get__(self.instance,None)
if key in self and isinstance(dict.__getitem__(self,key),attr.connection):
return thing.__get__(self.instance,None)
else:
return dict.__getitem__(self,key)
def __setitem__(self, key, value):
thing = dict.__getitem__(self,key)
if key in self and isinstance(dict.__getitem__(self,key),attr.Attribute):
thing.__set__(self.instance,value)
elif key in self and isinstance(dict.__getitem__(self,key),attr.connection):
thing.__set__(self.instance, value)
else:
dict.__setitem__(self,key,value)
class plusMinusAvg(attr.shaderNode):
type = "plusMinusAverage"
values1D = []
values2D = []
values3D = []
def addInput1D(self):
i = len(self.values1D)
print self
cmds.setAttr(self.fullpath() + ".input1D[" + str(i) + "]", 0)
newInput = pmaDict(self,
{"x": attr.Attribute("input1D[" + str(i) + "]", "float"),
"x_con": attr.connection("input1D[" + str(i) + "]")})
self.values1D.append(newInput)
def addInput2D(self):
i = len(self.values2D)
print self
cmds.setAttr(self.fullpath() + ".input2D[" + str(i) + "]", 0, 0, type="double2")
newInput = pmaDict(self,
{"xy": attr.Attribute("input2D[" + str(i) + "]", "float"),
"x": attr.Attribute("input2D[" + str(i) + "].input2Dx", "float"),
"y": attr.Attribute("input2D[" + str(i) + "].input2Dy", "float"),
"xy_con": attr.connection("input2D[" + str(i) + "]"),
"x_con": attr.connection("input2D[" + str(i) + "].input2Dx"),
"y_con": attr.connection("input2D[" + str(i) + "].input2Dy")})
self.values2D.append(newInput)
def addInput3D(self):
i = len(self.values3D)
print self
cmds.setAttr(self.fullpath()+".input3D["+str(i)+"]",0,0,0, type="double3")
newInput = pmaDict(self,
{"xyz": attr.Attribute("input3D["+str(i)+"]","double3"),
"x": attr.Attribute("input3D["+str(i)+"].input3Dx","float"),
"y": attr.Attribute("input3D["+str(i)+"].input3Dy","float"),
"z": attr.Attribute("input3D["+str(i)+"].input3Dz","float"),
"xyz_con": attr.connection("input3D["+str(i)+"]"),
"x_con": attr.connection("input3D["+str(i)+"].input3Dx"),
"y_con": attr.connection("input3D["+str(i)+"].input3Dy"),
"z_con": attr.connection("input3D["+str(i)+"].input3Dz")})
self.values3D.append(newInput)
def __init__(self, count1D=0, count2D=0, count3D=0):
attr.shaderNode.__init__(self)
for i in range(count1D):
self.addInput1D()
for i in range(count2D):
self.addInput2D()
for i in range(count3D):
self.addInput3D()
The problem lines are right here:
class plusMinusAvg(attr.shaderNode):
type = "plusMinusAverage"
values1D = []
values2D = []
values3D = []
You Are assigning the lists as class attributes. You are normally used to such an assignment working out because if you were to do something like values1d = blah in a method call, the assignment would implicitly be made on self. However, you never make another assignment: you just use the class-level list via methods such as append, __setitem__, etc. Therefore all instances use the same lists, defined in the class object.
To fix, move the three list assignments to within __init__:
self.values1D = []
self.values2D = []
self.values3D = []
This will ensure that each instance gets it's own list. Do that for all mutable attributes such as lists and dicts as a general rule to avoid the same type of problem in the future.
I want to access object (specifically its variables) from functions defined in different file. Let's see an example:
File 1 - grail.py
import enemies
class Encounter:
def __init__(self):
self.counter = 1
self.number = 0
self.who = "We've encountered no one."
def forward(self):
if self.counter == 1:
enemies.knightofni()
elif self.counter == 2:
enemies.frenchman()
else:
self.number = 42
self.who = "We've found the Grail!"
self.counter += 1
knight = Encounter()
for i in range(4):
print(str(knight.number) + " " + knight.who)
knight.forward()
File 2 - enemies.py (I probably need something in this file)
def knightofni():
Object.number = 1
Object.who = "We've encountered Knight of Ni."
def frenchman():
Object.number = 4
Object.who = "We've encountered French."
Output should show:
0 We've encountered no one.
1 We've encountered Knight of Ni.
4 We've encountered French.
42 We've found the Grail!
I know you can achieve the output by returning something from functions in file enemies.py, for example function frenchman() could look like:
def frenchman():
return [4, "We've encountered French."]
and in grail.py I should change code to collect what the frenchman() returns:
...
elif self.counter == 2:
spam = enemies.frenchman()
self.number = spam[0]
self.who = spam[1]
...
but it uses additional resources, makes the code longer, and more cumbersome in more complicated situations.
Is there a way to do the job directly on the object's variables but keeping functions in separate file?
EDIT
There are already answers to this question but maybe I will add clarification seeing doubt in one of the answers (citing comment to this answer):
I want it to be possible to add other "enemies" without making lengthy code in this place (so forward() is kind of a wrapper, place where it is decided what to do in different situations). It is also more readable if this functions are in different file.
Think of situation where there would be 100 "enemies" and each would need to change 100 variables which are lists with 1M entries each. Is there a better way than putting "enemies" into other file and changing variables directly in the file?
Problem
You need to hand over the object as argument.
In the function:
def knightofni(obj):
obj.number = 1
obj.who = "We've encountered Knight of Ni."
and when using it in the class:
enemies.knightofni(self)
Do the same for frenchman().
Full code
grail.py
import enemies
class Encounter:
def __init__(self):
self.counter = 1
self.number = 0
self.who = "We've encountered no one."
def forward(self):
if self.counter == 1:
enemies.knightofni(self)
elif self.counter == 2:
enemies.frenchman(self)
else:
self.number = 42
self.who = "We've found the Grail!"
self.counter += 1
knight = Encounter()
for i in range(4):
print(str(knight.number) + " " + knight.who)
knight.forward()
and enemies.py:
def knightofni(obj):
obj.number = 1
obj.who = "We've encountered Knight of Ni."
def frenchman(obj):
obj.number = 4
obj.who = "We've encountered French."
Output:
0 We've encountered no one.
1 We've encountered Knight of Ni.
4 We've encountered French.
42 We've found the Grail!
It is possible to do this, though I don't know why you would really want to do it this way.
In your forward and __init__ methods you'll notice that you are passing in self, which is the instance of Encounter you are operating on. That is why you can do self.number = 42 and get the correct number when you call knight.number.
Since self is just an object you can pass it into the functions in 'enemies.py'.
Try:
# grail.py
def forward(self):
if self.counter == 1:
enemies.knightofni(self)
elif self.counter == 2:
enemies.frenchman(self)
else:
self.number = 42
self.who = "We've found the Grail!"
self.counter += 1
#enemies.py
def knightofni(that):
that.number = 1
that.who = "We've encountered Knight of Ni."
def frenchman(that):
that.number = 4
that.who = "We've encountered French."