How to set up classes - class

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.

Related

Pass a class name as string argument to create instance

Is there any possible way to pass a class name/path as String argument to call it in code in runtime?
Im working with some legacy code and i have no way to change it globally. Creating new integration to it suggest me to create new copy of class X, rename it, and pass new instance of Y i have created manually. My mind tells me to pass Y as some kind of argument and never copy X again.
I don't quite understand why you (think that) you need to do what you are trying to do (why copy class in the first place rather than just using it? why pass classname around instead of the class itself?), but, yeah, you can instantiate classes by (fully qualified) name using reflection.
First you get a handle to the class itself:
val clazz = Class.forName("foo.bar.X")
Then, if constructor does not need any arguments, you can just do
val instance = clazz.newInstance
If you need to pass arguments to constructor, it gets a bit more complicated.
val constructor = clazz.getConstructors().find { c =>
c.getParameters().map(_.getParameterizedType) == args.map(_.getClass)
}.getOrElse (throw new Exception("No suitable constructor found")
// or if you know for sure there will be only one constructor,
// could just do clazz.getConnstructors.headOption.getOrElse(...)
val instance = constructor.newInstance(args)
Note though, that the resulting instance is of type Object (AnyRef), so there isn't much you can actually do with it without casting to some interface type your class is known to implement.
Let me just say it again: it is very likely not the best way to achieve what you are actually trying to do. If you open another question and describe your actual problem (not the solution to it you are trying to implement), you might get more helpful answers.

Using Enumeration for shared variables in Scala

Is it the right pattern to use Enumeration for holding shared variable values?
I am accepting arguments from the command line - arguments like "mongoUsername", "mongoPassword", "mongoDatabase" etc. - across a lot of different files, and want to remove the possibility of making a mistake while specifying the argument name.
I created an object as follows:
object CommonParams extends Enumeration {
val MONGO_USERNAME = "mongoUsername"
val MONGO_PASSWORD = "mongoPassword"
..
}
When accepting these parameters from the command line, the parameters will be read using CommonParams.MONGO_USERNAME rather than just "mongoUsername". This method works. My question is:
Is this the right way to do what I am trying to do?
I dont think I am using Enumeration correctly. What should I change?
What would I gain by declaring the CommonParams as follows:
.
object CommonParams extends Enumeration {
val MONGO_USERNAME = Value("mongoUsername")
val MONGO_PASSWORD = Value("mongoPassword")
..
}
If I declared CommonParams this way, I would have to use CommonParams.MONGO_USERNAME.toString each time instead of just using CommonParams.MONGO_USERNAME which is more verbose.
I understand that Enumeration can stand for a certain value being a "thing". However, I am holding a value inside an object attribute. What advantages would I get if I used the second way of declaring CommonParams?
In your first version, you should remove extends Enumeration, since you aren't actually using it.
The benefit of the second version is exactly that CommonParams.Values aren't strings, so that if you have e.g. a method accepting CommonParams.Value, you can't accidentally pass an invalid string. And also that you can get methods like CommonParams.values to list all values.

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.

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

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)

How do you set the class of an object to something else?

I've seen this recently and now I can't find it …
How do you set the class of an object to something else?
--Update: Well, in Pharo! Like:
d:=Object new. d setClass: Dictionary.
Only that it isn't actually setClass. How can you modify the class pointer of an object?
There is #primitiveChangeClassTo:.
It requires that both original and target class have the same class layout. For some strange reason it expects an instance of the target class as parameter, which is however not used.
So you would do
d := Object new.
d primitiveChangeClassTo: Dictionary new.
however this fails, since dictionaries have two instance variables but plain objects have none.
If you are into meta-programming, you might also be interesting in using any object as a class. I used that in Protalk to realize a prototype based language that works directly on top of Smalltalk.
The method #setClass: is used in some specific contexts and with different implementations (Check it with the Method Finder).
Object has some helpers to conver the current object in other sort of, as for example #asOrderedCollection, because this last permit the operation:
asOrderedCollection
"Answer an OrderedCollection with the receiver as its only element."
^ OrderedCollection with: self
HTH.
ok, then you can try something as:
d := Object new.
e := Dictionary new.
d become: e.
But, please, try #become: with caution, because in lot of situations it break the image.
Take a look at Class ClassBuilder. It creates the a new class, when you modify a class, and then switches the instances of the former to instances of the later. Therefor it should provide some method that does, what you ask for.