Initialize class reference - string

I get null value of instrumentRented
when I run
public class RentalAgreement
{
private MusicalInstrument instrumentRented;
public RentalAgreement(Customer renter,
RentalDate dateRented,
MusicalInstrument instrumentRented){
customer = renter;
rentalDate = dateRented;
instrumentRented = instrumentRented;
How to initialize MusicalInstrument reference in RentalAgreement?

Use this.instrumentRented = instrumentRented;
Since the parameter has the same name as the field attribute, you need to prefix with an explicit this to specify the scope.

You must instantiate a class with the new operator.
So somehwere in your code must do
instrumentRented = new MusicalInstrument();
before you access it. After you have done this you can execute functions from that class.
instrumentRented.doSomething();
In the above code you seem to pass it in in the constructor, so this means the caller has to instantiate it.
However I would advise to adopt a naming convention where you can see if a variable is a class member or a local variable. In your above code the local variable has the same name as the parameter, so it will not be set as a member variable, instead you assign it to itself. You might get a warning about this, depending on the evironment (Not sure about this but Eclipse definitely warns somethign like this). This is called shadowing, so what you need to do is:
this.instrumentRented = instrumentRented;

Related

How to set a puppet class variable from within a hiera_hash each loop?

hiera data
ae::namespace_by_fqdn_pattern:
'((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((client))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com': '/test/blah/regression/client'
'((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((server))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com': '/test/blah/regression/server'
class
class ae {
$namespace = hiera('ae::namespace')
$target_host_patterns = hiera('ae::target_host_patterns')
hiera_hash('ae::namespace_by_fqdn_pattern').each |String $pattern, String $ns| {
if $facts['networking']['fqdn'].match($pattern) {
$ae::namespace = "${ns}"
}
}
<snip>
... yields
Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Illegal attempt to assign to 'ae::enforcerd_namespace'. Cannot assign to variables in other namespaces (file: /etc/puppetlabs/code/environments/ar/modules/ae/manifests/init.pp, line: 21, column: 13) on node dfw-ubuntu1604-client02.pp-devcos.us-central1.gcp.dev.blah.com
... anyone here know how to do this correctly? trying to conditionally override that $ae::namespace variable but i'm too puppet-ignorant to know how to get it working : (
the loop and the pattern matching bits work. just can't figure out how to correctly set that class variable from within the hiera_hash().each loop.
How to set a puppet class variable from within a hiera_hash each loop?
You cannot. The associated block of an each() call establishes a local scope for each iteration. Variable assignments within apply to that local scope, and therefore last only for the duration of one execution of the block. You cannot anyway assign a new value to a variable during its lifetime, so even if you could assign to a class variable from within an each() call, it would be difficult to use that capability (and your approach would not work).
There are several ways you could approach the problem without modifying the form of the data. You could leverage the filter() function, for example, but my personal recommendation would be to use the reduce() function, something like this:
$namespace = lookup('ae::target_host_patterns').reduce(lookup('ae::namespace')) |$ns, $entry| {
$facts['networking']['fqdn'].match($entry[0]) ? { true => $entry[1], default => $ns }
}
That does pretty much exactly what your original code seems to be trying to do, except that the selected namespace is returned by the reduce() call, to be assigned to a variable by code at class scope, instead of the lambda trying to assign it directly. Note also that it takes care not only of testing the patterns but of assigning the default namespace when none of the patterns match, as it needs to do because you can only assign to the namespace variable once.
so the solution i landed on was to change the hiera data to:
ae::namespace : '/test/blah/regression'
ae::namespace_patterns: ['((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((client))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com', '((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((server))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com']
ae::namespace_by_pattern:
'((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((client))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com': '/test/paypal/regression/client'
'((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((server))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com': '/test/paypal/regression/server'
then the class code to:
$pattern = hiera_hash('ae::namespace_patterns').filter |$pattern| {
$facts['networking']['fqdn'] =~ $pattern
}
if length($pattern) {
$namespace = hiera('ae::namespace_by_pattern')[$pattern[0]]
} else {
$namespace = hiera('ae::namespace')
}
definitely still open to better answers. just what my own hacking produced as workable so far through much trial and error.

How to reference a class from a string which is part of a variable 3.7

I have just read a text file and extracted a string and stored it as a variable. This string also happens to be the name of a class I want to reference in order to use in a function for example. The "which_class" variable is the whichever class was stored in the file
I tried passing the which_class variable in as a parameter to the function. Removing the quotations seems to make it work but I am unsure how to do this.
class needed_for_func_one():
multiplier = 1.23
class needed_for_func_two():
multiplier = 1.15
def random_function(which_class):
print(123 * which_class.multiplier)
PSEUDO CODE
READ FROM FILE STORE STRING AS "which_class"
which_class = "needed_for_func_two"
random_function(which_class)
But this didn't work it just gave me an attribute error
the eval function could help you here.
random_function(eval(whichClass))
However, you should probably rethink whether you really want to it that way or if there is a much cleaner solution.
I think your question is related to this one
How you call the function depends if it is a global function or if it is inside an object.
globals()['call_this_function']() # this is probably what you need
or
getattr(from_this_object, 'call_this_function')()
first, to use a class you need an object of a class.
so if what you read is a name of the class or any other thing it does not matter, just use an if statement to decide what is inside that variable so-called "which_class".
then create an object like :
if which_class=="needed_for_func_one":
newObject = needed_for_func_one()
elseif which_class=="needed_for_func_two":
newObject = needed_for_func_two()
then use the print like :
print(123 * newObject.multiplier )

How to avoid duplication of class instances in Python?

What is a good way to avoid duplication of a class instance when it is created using the __init__() function.
This question is a result of this issue.
Context (using employee class example):
Lets say I have an employee class: __init__(self,name,dept)
I also have a method, employee.info(self) that prints out name and dept of any employee.
However a user could just add an employee by calling a=employee(args..). They could do it multiple times using the same instance variable a, but different employee names.
This will cause issues if they try to print a.info(), as each time a different employee name will be printed.
Is there a better way to do this? I know it is possible to have the __init__() "pass" and define a new method to create an instance.
Expect results:
>>Adam=employee('marketing')
>>Adam.info()
>>Adam works in marketing.
OR
>>a=employee('Adam','marketing')
>>a=employee('Mary','marketing')
>>Error: employee instance with identifier "a" already exists.
>>Use employee.update() method to modify existing record.
Is there a cleaner way of doing it? (as you might guess, I am still learning python).
Or is it good practice to write an explicit function (instead of a class method) to add new employees?
what you try is impossible, because in
a=employee('Adam','marketing')
a is not an object but a variable that points to the object employee('Adam','marketing').
When you do
a=employee('Mary','marketing')
you say to python that now, a must now not point to the object employee('Adam','marketing') but to the object employee('Mary','marketing'). And then, if you have no more variable to reference the object employee('Adam','marketing'), the garbage collector will destroy it.
You must consider that in python all is object, but not the variables that are only references to manipulate objects.
I have been racking my brains over the same problem and have finally managed to figure out a workaround :
Create a dictionary that stores the employee name and the related object like this :
total_emp_dict = {}
Add this inside the def __init__ of the class employee : total_emp_dict[name] = self. This will ensure to add each employee name as key and the object associated will be added as value.
Now create a new function outside & before the employee class is defined, let's call it create_new_emp. It will go like this :
#function to check and avoid duplicate assignment of instances
def create_new_emp(name, dept):
if name in total_emp_dict:
return total_emp_dict[name]
else:
return employee(name, dept)
When creating a any new employee, use this new function : a = create_new_emp("Adam", HR) instead of a = employee("Adam", HR)
Explanation : This function will ensure that duplicate assignment is not done. If "a" is already assigned to "Adam", this function will return object of "Adam" to "a", when called again. But if nothing is assigned to "a", then this function will handover to the attributes (name, dept) to employee class and create a new instance. This instance will then be assigned to "a".
I don't know if this is the best solution for this problem, but honestly this is the only solution I have found so far and it works great for me without much fuss / extra code space. Hope it works for you too! :)

How to modify safely CCLabelBMFont String after first allocation created?

I have a member named _label as an ivar member in class :
#interface CCHelloWorldLayer : CCLayer
{
CCLabelBMFont *_label;
}
in another codeblock: initializing with this line:
_label = [CCLabelBMFont labelWithString:#"Testing " fntFile:fntName];
question is this:
if I want to modify its text what Should I do ?
I dont see any method like:
[_label setString:#"Well.there is no such a method"];
if I do
_label = [CCLabelBMFont labelWithString:#"Testing " fntFile:fntName];
_label = [CCLabelBMFont labelWithString:#"Well.there is no such a method"
fntFile:fntName];
is first memory allocation autoreleasing it self ?
is it safe to recall labelWithString method repeately ?
(note:I dont use ARC in test project.and I wont.)
thanks in advice
There is a setString method but it appears to be "private". The +labelWithString method does create an autorelease object and can be used repeatedly. It looks like it creates a texture, so you would want to create a new texture each time (as opposed to trying to modify it).
In general though, if you want the autoreleased object to stick around, you should retain it and release it when you're done.
[_label setString:#"Well.there is no such a method"];
This method exists and you can call it like that. Try it, it works.
The method is not declared in the class but in CCLabelProtocol.

Error while adding data to ExpandoObject like dictionary

I am trying to understand c# dynamic. I have an ExpandoObject instance assigned to dynamic variable.
I understand ExpandoObject is implementing IDictionary. But the below assignment fails.
dynamic obj = new ExpandoObject();
obj["Test"] = "TestValue";
Console.WriteLine(obj.Test);
Can someone tell me where i am going wrong?
obj.Test="TestValue";
However the above statement seems to be working fine.
To do that, you need to cast the ExpandoObject to IDictionary<string, object>.
This is normal Expando usage:
obj.Test = "TestValue";
This is string-literal (or string variable) usage:
var d = (IDictionary<string, object>)obj;
d["Test"] = "TestValue";
string s = "Test";
d[s] = "TestValue";
If the interface implementation is explicit, you need to cast to a reference of the interface in order to access the members. I'm guessing this is what has happened here.

Resources