Can instances get their own copy of class level mutable defaults without using __init__? - class

I'm writing a metaclass to do some cool stuff, and part of its processing is to check that certain attributes exist when the class is created. Some of these are mutable, and would normally be set in __init__, but since __init__ isn't run until the instance is created the metaclass won't know that the attribute will be created, and raises an error. I could do something like:
class Test(meta=Meta):
mutable = None
def __init__(self):
self.mutable = list()
But this approach has several problems:
it forces the creation of a class attribute that is not the same type as the instance attribute
__init__ still has to shadow the class attribute, and Meta is not checking that
if __init__ doesn't shadow the class attribute I'll still get errors down the line (such as AttributeError: 'NoneType' object has no attribute 'append'), and trying to avoid such errors is part of the function of Meta
and last but not least, it violates DRY.
What I need is a way to have something like:
class Test(metaclass=Meta):
mutable = list()
But each instance will end up with its own copy of mutable.
The design goals are:
the attribute must exist in the class (type doesn't matter -- it is not checked)
at some point before the attribute is first used a copy of the attribute is placed in the instance
A desired sample run:
t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
t1.mutable # prints ['one']
t2.mutable # prints ['two']
Any ideas on how this can be accomplished?

There are at least three ways to do this:
Have the metaclass check all the attributes, and if they are one of the mutables (list, dict, set, etc.) replace the attribute with a descriptor that will activate on first access and update the instance with a fresh copy of the mutable.
Provide the descriptor from (1) as a decorator to be used when writing the class.
Have the metaclass add its own __init__ method to the class which when run:
calls the original __init__
then checks that the required attributes are present
Downsides (by method):
Extra effort is required if the class has a mutable attribute that should be shared across all instances.
The attribute in the class becomes a function in the class (possible mind-warp ;)
Move the point of error to class instantiation instead of class definition.
I prefer (2) is it gives complete control to the class author, simplifies those cases where the class-level mutable attribute should be shared amongst all the instances, and keeps the error at class definition.
Here's the decorator-descriptor:
class ReplaceMutable:
def __init__(self, func):
self.func = func
def __call__(self):
return self
def __get__(self, instance, owner):
if instance is None:
return self
result = self.func()
setattr(instance, self.func.__name__, result)
return result
and the test class:
class Test:
#ReplaceMutable
def mutable():
return list()
How it works:
Just like property, ReplaceMutable is a descriptor object with the same name as the attribute it is replacing. Unlike property, it does not define __set__ nor __delete__, so when code tries to rebind the name (mutable in the test above) in the instance Python will allow it to do so. This is the same idea behind caching descriptors.
ReplaceMutable is decorating a function (with the name of the desired attribute) that simply returns whatever the instance level attribute should be initialized with (an empty list in the example above). So the first time the attribute is looked up on an instance it will not be found in the instance dictionary and Python will activate the descriptor; the descriptor then calls the function to retrieve the initial object/data/whatever, stores it in the instance, and then returns it. The next time that attribute is accessed on that instance it will be in the instance dictionary, and that is what will be used.
Sample code:
t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
print(t1.mutable)
print(t2.mutable)

Related

How to get a value from a field inside an nested class?

I'm trying to get a value of a field from inside a nested class in Kotlin, however, I'm having some difficulties with the logic. Somewhere I saw that it is possible through an interface, but I don't know where to start.
A simple sample:
class ExternalClass {
class InternalClass {
val internalValue = 2
}
val externalValue = InternalClass().internalValue
}
fun main(args: Array<String>) {
print(ExternalClass().externalValue)
}
The easiest way (and most obvious) to achieve this would be to instantiate the InternalClass class inside the External, however, in some cases, it would be necessary to pass several parameters in the Internal's constructor, which would not be the case.
So how would it be possible to do this through an interface?
Any idea or insight will be welcome!
Thank you!
Taking a step back, it is nonsensical for the outer class to want to access a stateful property of some arbitrary instance of the nested class. There's no reason for an arbitrary instance's state to be useful. The only reason the outer class would need to access a property of the other class is if it is doing something with a specific instance of the inner class, in which case it would already have an instance of it on which to access its property.
In your example code, the nested class is weird because it defines a property that can only ever hold a value of 2. So every instance of the class is reserving memory for a property to hold a duplicate of that same value, even though it should really be a constant that is shared by all instances.
If the value you want to access is a constant (the same value for all instances), then it would make sense to want to access it regardless of instance because it doesn't have anything to do with a specific instance. To make it constant, it should be defined in a companion object like this. Then it can be accessed through the name of the nested class without creating an instance of it.
class ExternalClass {
class InternalClass {
companion object {
val internalValue = 2
}
}
val externalValue = InternalClass.internalValue
}
An interface would have nothing to do with this kind of thing.

Why do some Matlab class methods require "apparently" unnecessary output argument

After evolving my project code for months, I've finally hit a need to define a new class. Having to romp through my previous class definitions as a refresher of the conventions, I noticed that all constructors and property setters all have an output argument, even though nothing is assigned to it, e.g.:
function o = myConstructor( arg1, arg2, ... )
function o = set.SomeProperty( o, arg1 )
I've been looking through the documentation for upward of an hour without finding the explanation for this. It doesn't look like it depends on whether a function is defined in the class definition file or in its own separate m-file.
Can anyone please explain?
The best place to start is the documentation "Comparison of Handle and Value Classes". From the very top:
A value class constructor returns an object that is associated with the variable to which it is assigned. If you reassign this variable, MATLABĀ® creates an independent copy of the original object. If you pass this variable to a function to modify it, the function must return the modified object as an output argument.
A handle class constructor returns a handle object that is a reference to the object created. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. A function that modifies a handle object passed as an input argument does not need to return the object.
In other words, value classes need to return a modified object (which is a new object distinct from the original), while handle classes don't. The constructor of either class will always have to return an object, since it is actually constructing it.
Some good additional reading is "Which Kind of Class to Use", which links to a couple helpful examples of each type of class object. Looking at the DocPolynom value class example, you can see that property set methods have to return the modified object, while the dlnode handle class example only requires an output for its constructor. Note that you could still return an object from a handle class method (if desired), but it's not required.

Initializing an extended class with an instance when the parent class can't take itself as argument for the constructor

Ok. I am trying to extend a data structure class by making a subclass. The use case is that the program will already have an instance of the parent class and pass that to the constructor of the subclass. In other words, I have an instance of a parent class, A, and I want to feed it into an extended class constructor to get an instance of the extended class, B.
class child(Parent):
def __init__ (self, dataInstance=None):
super(child, self).__init__(dataInstance)
child.someparentmethod() # YES!
So if the Parent class could take an instance of itself in its constructor this would work (actually I'm dealing with multiple classes where some do and some do not). The hack-y thing I want to avoid is just passing the parent data structure as a property of another class:
class notChild():
def __init__ (self, dataInstance=None):
self.data = dataInstance
notChild.data.someparentmethod() # yuck.
I'm relatively new to OOP in python and I hope I'm overlooking something obvious. Thanks!
Ok. This is the solution I went with, which is specific to the implementation and I'd love to hear if there is a more general/pythonic way to do this:
class child(pandas.Panel4D):
def __init__ (self, d=None):
if isinstance(d, pandas.Panel4D):
d = d._data
super(child, self).__init__(d)
else:
super(child, self).__init__(d)
Essentially, if the child constructor is fed a parent instance, it accesses it's underlying data which is a class that the parent constructor can ingest.

How to set up classes

i am an engineering student enrolled in computer programming trying to understand a practice assignment for an upcoming lab and was wondering if someone could help me with this step of my program, Step: using The init method for the class takes the first formal parameter self and a list of [x, y] pairs v and stores the list as a class instance variable
It sounds like you are using Python, but next time you post a question, make sure you specify that and tag your question as such. You are looking for something like the following code:
class MyClassName(object):
def __init__(self, pairs):
self.pairs = pairs
Let's look at this line by line:
class MyClassName(object):
The first line declares a class called MyClassName. It extends object, which is not super important to understand right now, but is basically saying that MyClassName is a particular type of object.
def __init__(self, pairs):
The second line creates a function called __init__ which will be called when you instantiate an object of type MyClassName. This line also declares what parameters it takes. It sounds like you already know that the first argument has to be self, and the second parameter, pairs, is the list of [x,y] pairs. In python, we don't need to specify what type these parameters are, so we need only to name them (Some languages would require us to specify that pairs is going to be a list of pairs).
self.pairs = pairs
Now all we have to do is set the instance variable. Inside a class, self refers to this particular instance of the object. In other words, every time we create a variable of type MyClassName, the self keyword will refer to that particular instance of the object, rather than to all instances of MyClassName. So in this case, self.pairs refers to the variable pairs in this particular instance of MyClassName. On the other hand, pairs simply refers to the argument passed into the function __init__.
So, to put all this together, we have defined a class called MyClassName, then defined the __init__ function, and in it, we set the instance variable self.pairs to be equal to the pairs variable passed into __init__.
Last, I'll give a quick example of how to instantiate MyClassName:
my_list = [(1,1),(2,4),(3,9),(4,16)]
my_instance = MyClassName(my_list)
Good luck!
[Edit] Also, I agree with the first comment on your question. You need to be more clear and verbose in exactly what you are trying to accomplish and not leave it up to guess work. In this case, I think I could tell what you were trying to do, but it may not always be clear.

Scala: invoking superclass constructor

I am experiencing a weird behavior by Scala handling of superclass constructors.
I have a really simple class defined in the following way
package server
class Content(identifier:String,content:String){
def getIdentifier() : String = {identifier}
def getContent() : String = {content}
}
and a simple subclass
package server
class SubContent(identifier:String, content:String) extends Content(identifier, content+"XXX")){
override def getContent():String = {
println(content)
super.getContent
}
}
What's really strange is that in the subclass there are duplicates of the superclass attributes, so if i create a new object
var c = new SubContent("x","x")
the execution of
c.getContent
first prints out "x" (The valued provided to the subclass constructor), but returns "xXXX" (The value provided to the superclass constructor).
Is there any way to avoid this behavior? Basically what I'd like to have is that the subclass does not create its own attributes but rather just passes the parameters to the superclass.
It's doing exactly what you told it to do. You augmented the 2nd constructor parameter when passing it on to the superclass constructor and then you used the superclass' getContent to provide the value returned from the subclass' getContent.
The thing you need to be aware of is that constructor parameters (those not tied to properties because they're part of a case class or because they were declared with the val keyword) are in scope throughout the class body. The class' constructor is that part of its body that is outside any method. So references to constructor parameters in method bodies forces the constructor parameter to be stored in a field so it can have the necessary extent. Note that your println call in getContent is causing such a hidden constructor parameter field in this case.
Replying to comment "Is there an alternative way to define it in order to avoid this? Or at least, if I never refer to the parameters of the subclass constructors their fields will be allocated (Wasting memory)?":
If the only references to plain constructor parameters (*) is in the constructor proper (i.e., outside any method body, and val and var initializers don't qualify as method bodies) then no invisible field will be created to hold the constructor parameter.
However, If there's more you're trying to "avoid" than these invisible fields, I don't understand what you're asking.
(*) By "plain constructor parameters" I mean those not part of a case class and not bearing the val keyword.