How can I access attribute array in Parent class from Child class? Here is an example of my code that doesn't work
class Parent:
def __init__(self, x, y):
self.x = x
self.y = y
def __createArray(self): # Private function
x = self.x
y = self.y
array = []
array.append(f(x), f(y)) # f() is a random function
self.array = array
return array
class Child(Parent):
def __init__(self, x, y):
super().__init__(x, y)
def __create2ndArray(self): # Private function
x = self.x
y = self.y
# This line below doesn't work
array = self.array
Many people tell me to use super() function but I still don't know how. But it looks like I can't use super() in this situation since it only use for methods, not attributes
class Parent:
def __init__(self, x, y):
self.x = x
self.y = y
def _createArray(self): # Protected function - children cannot run private
x = self.x
y = self.y
array = []
f = lambda x: x
array.append(f(x)) # f() is a random function
array.append(f(y))
self.array = array
return array
class Child(Parent):
def __init__(self, x, y):
super().__init__(x, y)
def create2ndArray(self): # Public function - so that I can run it
super()._createArray()
x = self.x
y = self.y
# This line below doesn't work
array = self.array
print(array)
x = Child(3,4)
x.create2ndArray()
You have never ran __createArray() method in child so self.array was None
Related
I have written a code in which functions are called in each other. The working code is as follows:
import numpy as np
from scipy.optimize import leastsq
import RF
func = RF.roots
# residuals = RF.residuals
def residuals(params, x, y):
return y - func(params, x)
def estimation(x, y):
p_guess = [1, 2, 0.5, 0]
params, cov, infodict, mesg, ier = leastsq(residuals, p_guess, args=(x, y), full_output=True)
return params
x = np.array([2.78e-03, 3.09e-03, 3.25e-03, 3.38e-03, 3.74e-03, 4.42e-03, 4.45e-03, 4.75e-03, 8.05e-03, 1.03e-02, 1.30e-02])
y = np.array([2.16e+02, 2.50e+02, 3.60e+02, 4.48e+02, 5.60e+02, 8.64e+02, 9.00e+02, 1.00e+03, 2.00e+03, 3.00e+03, 4.00e+03])
FIT_params = estimation(x, y)
print(FIT_params)
where RF file is:
def roots(params, x):
a, b, c, d = params
y = a * (b * x) ** c + d
return y
def residuals(params, x, y):
return y - func(params, x)
I would like to remove residuals function from the main code and use it by calling from RF file instead i.e. by activating the code line residuals = RF.residuals. By doing so, error NameError: name 'func' is not defined will be appeared. I put func argument in RF's residuals function as def residuals(func, params, x, y): which will face to error TypeError: residuals() missing 1 required positional argument: 'y'; It seems the error is related to the forth argument of the residuals function in this sample because it will get error for 'func' if the func argument be placed after the y argument. I couldn't find out the source of the issue, but I guess it must be related to limitation of arguments in functions. I would be appreciated if anyone could guide me to understand the error and its solution.
Is it possible to bring residual function from the main code to the RF file? How?
The problem is that there's no global variable func in your file RF.py, hence it can't be found. A simple solution would be to add an additional parameter to your residuals function:
# RF.py
def roots(params, x):
a, b, c, d = params
y = a * (b * x) ** c + d
return y
def residuals(params, func, x, y):
return y - func(params, x)
Then, you can use it inside your other file like this:
import numpy as np
from scipy.optimize import leastsq
from RF import residuals, roots as func
def estimation(func, x, y):
p_guess = [1, 2, 0.5, 0]
params, cov, infodict, mesg, ier = leastsq(residuals, p_guess, args=(func, x, y), full_output=True)
return params
x = np.array([2.78e-03, 3.09e-03, 3.25e-03, 3.38e-03, 3.74e-03, 4.42e-03, 4.45e-03, 4.75e-03, 8.05e-03, 1.03e-02, 1.30e-02])
y = np.array([2.16e+02, 2.50e+02, 3.60e+02, 4.48e+02, 5.60e+02, 8.64e+02, 9.00e+02, 1.00e+03, 2.00e+03, 3.00e+03, 4.00e+03])
FIT_params = estimation(func, x, y)
print(FIT_params)
I need to have a seed so my random data is consistent while testing, but the seed I set when I define my_cv is not working--the data is different each time.
class customPDF(st.rv_continuous):
def _pdf(self,r):
return r**2
nmin = -1
nmax = 1
my_cv = customPDF(a=nmin, b=nmax,seed = 100)
def __init__(self):
self.y = random.uniform(-1,1)
self.x = my_cv.rvs(size=1)
self.distances = self.distanceToCandidates([self.x,self.y],election.candidates)
self.candidateIndexes = []
x = 0
for distance in self.distances:
self.candidateIndexes.append(x)
x +=1
I have a very simple class here:
Point = {}
function Point:new(x,y)
local self = {}
self.x = x
self.y = y
--------------------
function self.set(x,y)
self.x = x
self.y = y
end
function self.get()
return {self.x,self.y}
end
--------------------
return self
end
Every instance has all methods in it.
It's a huge waste of memory isn't it?
How do I store an instance's data but only a single copy of their methods?
Your solution is metatables. By setting the __index field you can easily "reroute" nil values to the Point table itself. So by storing the methods in Point, you aren't taking up so much memory!
Point = {}
function Point.set(self, x,y)
self.x = x
self.y = y
end
function Point.get(self)
return {self.x,self.y}
end
function Point.new(self, x,y)
local point = setmetatable({},{__index = Point})
point.x = x
point.y = y
return point
end
print(table.unpack(Point:new(1,2):get()))
I have defined two typeclasses:
trait WeakOrder[-X] { self =>
def cmp(x: X, y: X): Int
def max[Y <: X](x: Y, y: Y): Y = if (cmp(x, y) >= 0) x else y
def min[Y <: X](x: Y, y: Y): Y = if (cmp(x, y) <= 0) x else y
}
trait Lattice[X] { self =>
def sup(x: X, y: X): X
def inf(x: X, y: X): X
}
I would like to do the following:
trait TotalOrder[-X] extends Lattice[X] with WeakOrder[X] { self =>
def sup(x: X, y: X): X = max(x, y)
def inf(x: X, y: X): X = min(x, y)
}
But this is impossible because contravariant type X appears at a covariant position (the returning value of sup and inf).
However, semantically this is correct: max and min with the type signature max[Y <: X](x: Y, y: Y): Y encodes the fact that the returning value of max / min must be one of the two arguments.
I tried to do the following:
trait TotalOrder[-X] extends Lattice[X] with WeakOrder[X] { self =>
def sup[Y <: X](x: Y, y: Y): Y = max(x, y)
def inf[Y <: X](x: Y, y: Y): Y = min(x, y)
}
However, the method def sup[Y <: X](x: Y, y: Y): Y cannot inherit def sup[X](x: X, y: X): X. The compiler complains that the type signature does not match. But the former one (with the on-site variance annotation) imposes a stronger type restrictions than the latter signature. Why the former one cannot inherit the latter one? How can I bypass the contravariant type restrictions on TotalOrder[-X] (semantically, a total order is contravariant)?
This is not semantically correct. It should be clear from the definition of covariant and contravariant, but I'll try to give an example:
Suppose we have hierarchy of entities:
class Shape(s:Float)
class Circle(r:Float) extends Shape(Math.PI.toFloat * r * r)
And let's assume that it's possible to create contravariant orders, as you tried:
trait CircleOrder extends TotalOrder[Circle] {
// compare by r
}
trait ShapeOrder extends TotalOrder[Shape] {
// compare by s
}
By definition of contravariants, as Shape <: Circle,
CircleOrder <: ShapeOrder
(CircleOrder is supertype of ShapeOrder)
Suppose we have client that takes CircleOrder as the argument
and uses it to compare circles:
def clientMethod(circleOrder:TotalOrder[Circle]) = {
val maxCircle = circleOrder.max(???, ???) // expected to return Circle
maxCircle.r // accessing field that is present only in circle
}
Then, by definition of inheritance, it should be possible to pass
ShapeOrder instead of CircleOrder (remember, ShapeOrder is subtype):
clientMethod(new ShapeOrder {/*...*/})
Obviously it will not work, as client still expects order to return Circles, not Shapes.
I think in your case the most reasonable approach will use regular generics.
Update
This is how you can ensure type safety, but it's a bit ugly.
trait WeakOrder[-X] {
def cmp(x: X, y: X): Int
def max[T](x: X with T, y: X with T): T =
if (cmp(x, y) >= 0) x else y
def min[T](x: X with T, y: X with T): T =
if (cmp(x, y) <= 0) x else y
}
trait Lattice[X] {
def sup[T](x: X with T, y: X with T): T
def inf[T](x: X with T, y: X with T): T
}
trait TotalOrder[-X] extends Lattice[X] with WeakOrder[X] {
def sup[T](x: X with T, y: X with T): T = max(x, y)
def inf[T](x: X with T, y: X with T): T = min(x, y)
}
I'm trying to define the operator type add when it comes to my class Point. Point is exactly what it seems, (x, y). I can't seem to get the operator to work though because the code keeps printing the <main.Point...>. I'm pretty new to this stuff, so can someone explain what I am doing wrong? Thanks. Here is my code:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)
Your add function is working as intended. It's your print that's the problem. You're getting an ugly result like <__main__.Point object at 0x027FA5B0> because you haven't told the class how you want it to display itself. Implement __str__ or __repr__ so that it shows a nice string.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __repr__(self):
return "Point({}, {})".format(self.x, self.y)
p1 = Point(3,4)
p2 = Point(5,6)
p3 = p1 + p2
print(p3)
Result:
Point(8, 10)