Inheritance of private and protected methods in Python

Python has no privacy model, there are no access modifiers like in C++, C# or Java. There are no truly ‘protected’ or ‘private’ attributes. Names with a leading double underscore and no trailing double underscore are mangled to protect them from clashes when inherited. Subclasses can define their own __private() method and these will not … Read more

How do I access Class member variables?

The answer, in a few words In your example, itsProblem is a local variable. Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be: class Example(object): def __init__(self): self.itsProblem = “problem” theExample = Example() print(theExample.itsProblem) But if you want a true class … Read more

array_unique for objects?

array_unique works with an array of objects using SORT_REGULAR: class MyClass { public $prop; } $foo = new MyClass(); $foo->prop = ‘test1’; $bar = $foo; $bam = new MyClass(); $bam->prop = ‘test2’; $test = array($foo, $bar, $bam); print_r(array_unique($test, SORT_REGULAR)); Will print: Array ( [0] => MyClass Object ( [prop] => test1 ) [2] => MyClass … Read more

When to use an object instance variable versus passing an argument to the method

Since you’re referring to instance variables, I’m assuming that you’re working in an object-oriented language. To some degree, when to use instance variables, how to define their scope, and when to use local variables is subjective, but there are a couple of rules of thumb you can follow whenever creating your classes. Instance variables are … Read more

Is it possible to overload Python assignment?

The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have been provided to change its behavior. However, assignment to a member in a class instance can be controlled as you want, by overriding .__setattr__(). class MyClass(object): def __init__(self, x): self.x = x … Read more

How to add a new method to a php object on the fly?

You can harness __call for this: class Foo { public function __call($method, $args) { if (isset($this->$method)) { $func = $this->$method; return call_user_func_array($func, $args); } } } $foo = new Foo(); $foo->bar = function () { echo “Hello, this function is added at runtime”; }; $foo->bar();

What is the purpose of “!” and “?” at the end of method names?

It’s “just sugarcoating” for readability, but they do have common meanings: Methods ending in ! perform some permanent or potentially dangerous change; for example: Enumerable#sort returns a sorted version of the object while Enumerable#sort! sorts it in place. In Rails, ActiveRecord::Base#save returns false if saving failed, while ActiveRecord::Base#save! raises an exception. Kernel::exit causes a script … Read more