How to Make That an Object of the Same Class Become the Return Value of Initializer

How can I make that an object of the same class become the return value of initializer?

As the error states UIImage is immutable. What you can do is to get a CGImage from your outputImage and use UIImage init(cgImage: CGImage) initializer to initialize a new image from it:

extension UIImage {
convenience init?(layer: CALayer) {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, 0)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
layer.render(in: context)
guard let outputImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else {
return nil
}
self.init(cgImage: outputImage)
}
}

passing an object to a function in a the same class to initialize the values, but not by reference

doesn't it have to be passed using ref, out, or returning a different Person?

Nope.

Consider the stack and the heap. For primitive values (integers are a good example) they just exist on the stack. When they're passed to a method, a copy of them is supplied to that next frame on the stack.

For reference types however, what gets passed to the next frame on the stack? The reference does. Consider it like a "pointer". A simple value which indicates where in the heap the actual object is.

This is only ever invoked once in your example:

new Person()

So only one instance of Person exists in memory. The "pointer" to that instance was copied into the stack frame. If you change the value of the "pointer" itself:

private void Initialize(Person person)
{
person = new Person();
}

Then no effect would come to the original instance. But that's not what happened. The "pointer" was followed and the instance was changed:

person.Name = "";

The variable person was unaffected by this statement. No operation was made to modify it. But a property on the object in memory that the person variable points to was modified. That change is visible anywhere a reference to that object exists, inside or outside the method, anywhere in the system.

Initialization in return statements of functions that return by-value

You have to be careful with cppreference.com when diving into such nitty-gritty, as it's not an authoritative source.

So which object exactly is copy-initialized as described at cppreference.com for return statements?

In this case, none. That's what copy elision is: The copy that would normally happen is skipped. The cppreference (4) clause could be written as "when returning from a function that returns by value, and the copy is not elided", but that's kind of redundant. The standard: [stmt.return] is a lot clearer on the subject.

To convert from A&& to A A's move constructor is used, which is also why NRVO is disabled here. Are those the rules that apply in this case, and did I understand them correctly?

That's not quite right. NRVO only applies to names of non-volatile objects. However, in return std::move(local);, it's not local that is being returned, it's the A&& that is the result of the call to std::move(). This has no name, thus mandatory NRVO does not apply.

I think this should be an Lvalue to rvalue conversion:

The A&& returned by std::move() is decidedly not an Lvalue. It's an xvalue, and thus an rvalue already. There is no Lvalue to rvalue conversion happening here.

but A a2(no_nrvo()); is a direct initialization. So this also touches on the first case.

Not really. Whether a function has to perform copy-initialization of its result as part of a return statement is not impacted in any way by how that function is invoked. Similarly, how a function's return argument is used at the callsite is not impacted by the function's definition.

In both cases, an is direct-initialized by the result of the function. In practice, this means that the compiler will use the same memory location for the an object as for the return value of the function.

In A a1(nrvo());, thanks to NRVO, the memory location assigned to local is the same as the function's result value, which happens to be a1 already. Effectively, local and a1 were the same object all along.

In A a2(no_nrvo()), local has its own storage, and the result of the function, aka a2 is move-constructed from it. Effectively, local is moved into a2.

Is it possible to use an initializer on a function return value?

While it isn't possible to do exactly what you are asking, you can use the Builder design pattern to increase readability.

Something along these lines:

var myClassInstance = myFactory.CreateMyClass()
.WithMyPropertyA("blah")
.WithMyPropertyB("Bleh");

This can be done with either extension methods or wrapping myFactory in a builder class of your own.

In swift, how do I return an object of the same type that conforms to a protocol

Autocomplete will help you, but basically, if Foo is a class, you just need a method which matches the exact signature of the method in your protocol:

class Foo {}

protocol JSONInitializable {
static func initialize(fromJSON: [String : AnyObject]) throws -> Self?
}

extension Foo: JSONInitializable {
static func initialize(fromJSON: [String : AnyObject]) throws -> Self? {
return nil
}
}

As a note here, you will have to, within this method, replace all instances of Foo with Self. If you want to use a constructor, it will have to be one marked as required.

With this in mind, it probably makes more sense to change your protocol to requiring an initializer rather than a static method called initialize, in which case, take a look at Blake Lockley's answer. However, this answer stands to answer the question of how to deal with Self in protocols, as there are certainly cases where we might want a method that returns Self that isn't an initializer.


If Foo is not a class, it is a value type which cannot be subclasses, and as such, we return the name of the type:

struct Foo: JSONInitializable {
static func initialize(fromJSON: [String : AnyObject]) throws -> Foo? {
return nil
}
}
enum Foo: JSONInitializable {
case One, Two, Three

static func initialize(fromJSON: [String : AnyObject]) throws -> Foo? {
return nil
}
}

The reason you need to return Self? from the method in the case of a class is because of inheritance. The protocol declares that if you conform to it, you will have a method called initialize whose return type will be an optional version of whatever you are.

If we write Foo's initialize method as you wrote it, then if we subclass Foo with Bar, then now we have broken our conformance to the protocol. Bar has inherited the conformance to the protocol from Foo, but it doesn't have a method which is called initialize and returns Bar?. It has one that returns Foo.

Using Self here means that when our subclasses inherit this method, it will return whatever type they are. Self is Swift's equivalent of Objective-C's instancetype.

In Python, how to initialize a class attribute from the return value of a class method?

You cannot do it in class definition because class object has not been created yet.
After the class definition, you could definitely do something like this -

Custom.mapping['key'] = Custom.get_choices()

Although the recommended way to do this would be to use a metaclass.

class CustomMetaClass(type):

def __init__(cls, classname, bases, attrs):
super(CustomMetaClass, cls).__init__(classname, bases, attrs)

cls.mapping['key'] = cls.get_choices()

class Custom(metaclass = CustomMetaClass): # assuming you are using python 3

mapping = {}

@classmethod
def get_choices(cls):
# add your custom code here
pass

With that said, that is an Object Oriented solution to the problem. you can ofcourse use some function to generate choices thus ending the need to use metaclass.

For Edited Question:-

In that case, I think you should just maintain a file named 'choices.py' as you yourself suggested and use them in your mapping, instead of get_choices class method. You don't need to unnecessarily make classes for each model if all you want to do is store choices. Just use dicts and constants.

If your classes needs to be generated dynamically, say from db, then you need to create separate model for storing choices.

class CustomModelChoices(models.Model):

model_name = models.StringField(db_field = 'mn')
choices = models.DictField(db_field = 'ch')

class CustomModel(models.Model):

_choice_generator = CustomModelChoices

mapping = {
'key': CustomModelChoices.objects.get(model_name = 'CustomModel').choices
}

This is just a raw design, might need to be improved a lot, but something on these lines.

How to return a value from __init__ in Python?

__init__ is required to return None. You cannot (or at least shouldn't) return something else.

Try making whatever you want to return an instance variable (or function).

>>> class Foo:
... def __init__(self):
... return 42
...
>>> foo = Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() should return None

How to initialize values using Set Methods in JAVA, when using Composition?

What I can gather from your screenshots, do the following to remove the NullPointerException error:

Initialize the variable course1 as private Course course1 = new Course() in your Student.java class. Do the same for course2.



Related Topics



Leave a reply



Submit