Automatically initialize instance variables?
You can use a decorator:
from functools import wraps
import inspect
def initializer(func):
"""
Automatically assigns the parameters.
>>> class process:
... @initializer
... def __init__(self, cmd, reachable=False, user='root'):
... pass
>>> p = process('halt', True)
>>> p.cmd, p.reachable, p.user
('halt', True, 'root')
"""
names, varargs, keywords, defaults = inspect.getargspec(func)
@wraps(func)
def wrapper(self, *args, **kargs):
for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
setattr(self, name, arg)
for name, default in zip(reversed(names), reversed(defaults)):
if not hasattr(self, name):
setattr(self, name, default)
func(self, *args, **kargs)
return wrapper
Use it to decorate the __init__
method:
class process:
@initializer
def __init__(self, PID, PPID, cmd, FDs, reachable, user):
pass
Output:
>>> c = process(1, 2, 3, 4, 5, 6)
>>> c.PID
1
>>> dir(c)
['FDs', 'PID', 'PPID', '__doc__', '__init__', '__module__', 'cmd', 'reachable', 'user'
What happens when you initialize instance variables outside of __init__
The __init__
method is not special. The only thing that makes __init__
interesting is the fact that it gets called when you call MyClass()
.
The following are equivalent:
# Set inside __init__
class MyClassA:
def __init__(self):
self.x = 0
obj = MyClassA()
# Set inside other method
class MyClassB:
def my_initialize(self):
self.x = 0
obj = MyClassB()
obj.my_initialize()
# Set from outside any method, no self
class MyClassC:
pass
obj = MyClassC()
obj.x = 0
What makes an instance variable is when you assign it, and that can happen anywhere. Also note that self
is not special either, it's just an ordinary function parameter (and in fact, you can name it something other than self
).
so that the memory is properly reserved for this variable per instance.
You do not need to "reserve memory" in Python. With ordinary object instances, when you assign self.x = 0
or obj.x = 0
, it is kind of like putting a value in a dictionary. In fact,
# This is sometimes equivalent, depending on how obj is defined
obj.__dict__['x'] = 0
Ruby - automatically initialize class instance variables of child classes without inheriting the value
You don't have to initialize the class variable when it is being inherited. The Ruby style is to return and assign default value when the variable has not been set and is being accessed for the first time.
Just create another class method for that:
class AbstractClass
def self.metadata
@metadata ||= []
end
def self.add_metadata(metadata)
self.metadata << metadata
end
end
class ChildClass1 < AbstractClass
add_metadata(:child_class1)
end
class ChildClass2 < AbstractClass
add_metadata(:child_class2)
end
AbstractClass.metadata # => []
ChildClass1.metadata # => [:child_class1]
ChildClass2.metadata # => [:child_class2]
Automatically initialize multiple instance of class
You can create a class FishPopulation
and then store there all the Fish
you need based on the size argument. For example, something like this would work:
import numpy as np
class Fish:
def __init__(self):
self.resistance_threshold = np.random.normal(0, 1)
class FishPopulation:
def __init__(self, size=1000):
self.size = size
self.fishes = [Fish() for _ in range(size)]
You can iterate over it like this:
fish_population = FishPopulation(size=10)
for fish in fish_population.fishes:
print(fish.resistance_threshold)
>>>
-0.9658927669391391
-0.5934917229482478
0.8827336199040103
-1.5729644992077412
-0.7682070400307331
1.464407499255235
0.7724449293785645
-0.7296586180041732
-1.1989783570280217
0.15716170041128566
And you can access their indexes like this:
print(fish_population.fishes[0].resistance_threshold)
>>> -0.9658927669391391
If we define own constructor then how does java initialize instance variables to their default value
Java assigns default values to instance variables using default constructor.
No, not really. It automatically assigns default values to all members prior to executing any constructor.
But if we define our own constructor then how does java give default values (because when we write our constructor then, then default constructor is not added).
It still assigns default values to all members.
class Test {
int i;
Object ref;
Test() {
System.out.println(i);
System.out.println(ref);
}
public static void main(String[] args) {
new Test();
}
}
Output:
0
null
default value for instance variable in the class body
Field initialization occurs before the constructor body is executed. It's helpful in some occasions, for example if you have multiple constructors, and the field should have the same initial value. In your example, you always want to start with an empty list, so you avoid null pointer exceptions. This is indeed a good practice for collections in general.
Related Topics
Preserving Styles Using Python's Xlrd,Xlwt, and Xlutils.Copy
Permanent Fix for Opencv Videocapture
Difference in Boto3 Between Resource, Client, and Session
Beautifulsoup Not Grabbing Dynamic Content
Purpose of Calling Function Without Brackets Python
Python Script for Minifying CSS
Floating Point Math in Different Programming Languages
Is There an R Equivalent of the Pythonic "If _Name_ == "_Main_": Main()"
Convert Backward Slash to Forward Slash in Python
Why Is Ruby More Suitable for Rails Than Python
Automatically Initialize Instance Variables
How to Convert a File into a Dictionary
Best Way to Find the Months Between Two Dates
What Is the Good Python3 Equivalent for Auto Tuple Unpacking in Lambda
Module' Object Has No Attribute 'Loads' While Parsing JSON Using Python