How to combine the following 2 classes into one class, Rectangle, so that a Rectangle object can be created either by rect = Rectangle(side_a, side_b) or rect = Rectangle(side_a, area)?
class Rectangle1:
def __init__(self, side_a, side_b):
self.side_a = side_a
self.side_b = side_b
self.area = self.side_a * self.side_b
class Rectangle2:
def __init__(self, side_a, area):
self.side_a = side_a
self.area = area
self.side_b = self.area / side_a
As demonstrated here.
class Rectangle:
def __init__(self, a, b):
""" Create a new rectangle with sides of length a and b.
"""
self.side_a = side_a
self.side_b = side_b
self.area = self.side_a * self.side_b
#classmethod
def from_sides(cls, a, b):
return cls(a, b)
#classmethod
def from_area(cls, a, o):
return cls(a, o/a)
You can then create rectangles as
r1 = Rectangle.from_sides(s1, s2)
r2 = Rectangle.from_area(s1, a)
You cannot overload methods with methods of the same name. Well, you can, but only the last one is then visible.
The other option is keyword-only arguments.
With Python 3, you could write:
class Rectangle:
def __init__(self, side_a, *, side_b=None, area=None):
self.side_a = side_a
if side_b is None and area is None:
raise Exception("Provide either side_b or area")
if side_b is not None and area is not None:
raise Exception("Provide either side_b or area, not both")
if side_b is not None:
self.side_b = side_b
self.area = self.side_a * self.side_b
else:
self.area = area
self.side_b = self.area / side_a
using * in the middle forces the user to use keyword argument passing from that point, not allowing positionnal, which prevents the mistakes. And the (rather clumsy) manual checking for None logic ensures that one and only one keyword parameter is passed to the constructor. The inside is complex, but the interface is safe to use, that's the main point here.
r = Rectangle(10,area=20)
r2 = Rectangle(10,side_b=20)
r3 = Rectangle(10,20) # doesn't run, need keyword arguments
This may not be what you're looking for, but here's what I came up with:
class Rectangle:
def __init__(self, side_a, side_b = None, area = None):
self.side_a = side_a
if area == None:
self.area = side_a * side_b
self.side_b = side_b
else:
self.side_b = area / side_a
self.area = area
You could do
class Combined:
def __init__(self, a, b=None, area=None):
self.a = a
self.area = self.a * b if b else area
self.b = self.area / self.a
I would share a basic example to use default as well as parametrized constructor in python. You need to declare as well as assign variable in function definition itself for default constructor.
class Person:
def __init__(self,name="",age=0):
self.name=name
self.age=age
def __int__(self,name,age):
self.name=name
self.age=age
def showdetails(self):
print("\nName is "+str(self.name)+" and age is "+str(self.age))
p1=Person("Sam",50)
p1.showdetails()
p2=Person()
p2.showdetails()
Output:
Name is Sam and age is 50
Name is and age is 0
Related
I think to have a use case for the factory pattern method in python and have two ideas how to implement it (see below). Both work, but are they really the same? Option2 looks much clearer to me, despite having a few more lines. Is my gut feeling right? Or is there a third better option?
Option 1
def inner_factory_func(a):
class Inner:
def __init__(self, b):
self.a = a
self.b = b
def call(self):
return self.a + self.b
return Inner
inner_factory = inner_factory_func('a')
inner = inner_factory('b')
res = inner.call() # ='ab'
Option 2
class Inner:
def __init__(self,a,b):
self.a = a
self.b = b
def call(self):
return self.a+self.b
class InnerFactory:
def __init__(self,a ):
self.a = a
def create(self,b) -> Inner2:
return Inner(self.a,b)
inner_factory = InnerFactory('a')
inner = inner_factory.create('b')
res = inner.call() # ='ab'
I'm testing some code for a course OOP, but I run into a problem. I am programming a circle and a cylinder, with the circle class also in the init of the cylinder. I have 2 arguments for the cylinder, but when I give 2 arguments, it's said that I only need 1 and if I give one argument than it gaves the output one is missing.
with the variable a it works, but the error is in variable b. What do I wrong
import math
class CCircle:
def __init__(self):
self._radius = 0
#property
def area(self):
return self._radius**2 * math.pi
#area.setter
def area(self, value):
self._radius = math.sqrt(value / math.pi)
#property
def circumference(self):
return self._radius * 2 * math.pi
#circumference.setter
def circumference(self, value):
self._radius = value / (2 * math.pi)
class CCylinder:
def __init__(self, radius, height):
self._circle = CCircle(radius)
self._height = height
#property
def circumference(self):
return self._circle.circumference
#property
def ground_area(self):
return self._circle.area
#property
def total_area(self):
return self._circle.area + self._height * self._circle.circumference
#property
def volume(self):
return self._circle.area * self._height
a = CCircle()
b = CCylinder(1,4)
init() takes 1 positional argument but 2 were given
You should have your CCircle class start like this
class CCircle:
def __init__(self, radius=0):
self._radius = radius
so that you get the default radius of 0 that you seem to want, but can also initialize it with a radius value like you're doing in the init code of your CCylinder class.
The problem is with this line:
self._circle = CCircle(radius)
but __init__ for the CCircle class does not take any arguments (except for self) so this is causing the error.
You might have had a package folder locally at the place where the .py file is , delete that and that should solve your issue
Just trying to create a simple toy example to calculate the surface area of a pyramid:
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
#super().__init__(**kwargs)
def area(self):
return self.length * self.width
def perim(self):
return 2 * (self.length + self.width)
class Square(Rectangle):
def __init__(self, length, **kwargs):
super().__init__(length = length, width = length, **kwargs)
class Triangle:
def __init__(self, base, height, **kwargs):
self.base = base
self.height = height
super().__init__(**kwargs)
def tri_area(self):
return 0.5 * self.base * self.height
class Pyramid(Square, Triangle):
def __init__(self, base, slant, **kwargs):
kwargs["height"] = slant
kwargs["length"] = base
super().__init__(base = base, **kwargs)
def surf_area(self):
return super().area() + 4 * super().tri_area()
p = Pyramid(2,4)
p.surf_area()
But this gives me an error of
AttributeError Traceback (most recent call last)
<ipython-input-154-d97bd6ab2312> in <module>
1 p = Pyramid(2,4)
----> 2 p.surf_area()
<ipython-input-153-457095747484> in surf_area(self)
6
7 def surf_area(self):
----> 8 return super().area() + 4 * super().tri_area()
<ipython-input-151-8b1d4ef9dca9> in tri_area(self)
5 super().__init__(**kwargs)
6 def tri_area(self):
----> 7 return 0.5 * self.base * self.height
AttributeError: 'Pyramid' object has no attribute 'base'
The online resources don't seem to give much of a conceptual understanding of **kwargs too well (or they're written in too much a labrintyine manner for a beginner). Does this somehow have to do with the fact that **kwargs as an iterable need to be exhausted completely before going to the next call?
I can sort of understand why you'd be confused. The main trick to realise is this: absolute bottom line, kwargs is not something magical. It is just a dictionary holding key value pairs. If a call requires more positional arguments than provided, it can look into keyword arguments and accept some values. However, kwargs does not invoke some magic that associates all names provided as a self.<some_name_here> .
So, first to just get a visual understanding of what's going on, what you should do when you don't understand a piece of code is making sure it runs how you think it does. Let's add a couple print statements and see what's happening.
Version 1:
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
print(f"in rectangle. length = {self.length}, width = {self.width}")
def area(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, length, **kwargs):
print("in square")
super().__init__(length = length, width = length, **kwargs)
class Triangle:
def __init__(self, base, height, **kwargs):
print("in triangle")
self.base = base
self.height = height
super().__init__(**kwargs)
def tri_area(self):
return 0.5 * self.base * self.height
class Pyramid(Square, Triangle):
def __init__(self, base, slant, **kwargs):
print("in pyramid")
kwargs["height"] = slant
kwargs["length"] = base
super().__init__(base = base, **kwargs)
def surf_area(self):
print(f"area : {super().area()}")
print(f"tri_area : {super().tri_area()}")
return super().area() + 4 * super().tri_area()
p = Pyramid(2,4)
p.surf_area()
Output:
in pyramid
in square
in rectangle. length = 2, width = 2
area : 4
#and then an error, note that it occurs when calling super().tri_area()
#traceback removed for brevity.
AttributeError: 'Pyramid' object has no attribute 'base'
I suspect this already breaks some assumptions you had about how the code runs. Notice that the triangle's init was never called. But let's get rid of the parts that work fine, and add an additional print statement. I will also take the liberty of calling it with a different value for first argument, something that pops out easier.
Version 2:
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
print(f"in rectangle. length = {self.length}, width = {self.width}")
print(f"kwargs are: {kwargs}")
class Square(Rectangle):
def __init__(self, length, **kwargs):
print("in square")
super().__init__(length = length, width = length, **kwargs)
class Triangle:
def __init__(self, base, height, **kwargs):
print("in triangle")
self.base = base
self.height = height
super().__init__(**kwargs)
def tri_area(self):
return 0.5 * self.base * self.height
class Pyramid(Square, Triangle):
def __init__(self, base, slant, **kwargs):
print("in pyramid")
kwargs["height"] = slant
kwargs["length"] = base
super().__init__(base = base, **kwargs)
def surf_area(self):
print(f"tri_area : {super().tri_area()}")
return super().tri_area()
p = Pyramid(10000,4)
p.surf_area()
Output:
in pyramid
in square
in rectangle. length = 10000, width = 10000
kwargs are: {'base': 10000, 'height': 4}
#error with traceback
AttributeError: 'Pyramid' object has no attribute 'base'
Bottom line: the kwargs holds a key with the name base, but this has no relation to self.base. However, my recommendation is to get rid of the whole class structure, and spend some time playing around with any basic function, get rid of the extra stuff.
Say, a demonstration:
def some_func(a, b, **kwargs):
print(a, b)
print(kwargs)
some_func(1, 2)
some_func(1, 2, c=42)
some_func(a=1, c=42, b=2)
def other_func(a, b, **look_at_me):
print(a, b)
print(look_at_me)
other_func(1, 2)
other_func(1, 2, c=42)
other_func(a=1, c=42, b=2)
These two chunks produce the same outputs. No magic here.
Output:
1 2
{}
1 2
{'c': 42}
1 2
{'c': 42}
When you added the classes into the mix, and inheritance, there's too many things happening at once. It is easier to miss what happens, so it's a good idea to use smaller code samples.
I'm trying to initialize sT from an imported module. And getting the error:
sT = SierpinskiTriangle(self.dimensions, 50000, 0.5, vertices)
TypeError: SierpinskiTriangle() takes exactly 1 argument (4 given)
and I'm not really sure why or what I've done wrong.
sT = SierpinskiTriangle(self.dimensions, 50000, 0.5, vertices)
And I've imported this from another file:
class Fractal(Canvas, Point):
def __init__(self, dimensions, num_points, ratio, vertices):
self.dimensions = dimensions
self.num_points = num_points
self.r = ratio
self.vertices = vertices
def frac_x(self, r):
return int((self.dimensions["max_x"] - \
self.dimensions["min_x"]) * r) + \
self.dimensions["min_x"]
def frac_y(self, r):
return int((self.dimensions["max_y"] - \
self.dimensions["min_y"]) * r) + \
self.dimensions["min_y"]
def SierpinskiTriangle(Fractal):
def __init__(self, dimensions, num_points, ratio, vertices):
Fractal.__init__(self, dimensions, num_points, ratio, vertices)
Edit, here's the Point class:
class Point(object):
def __init__(self, x = 0.0, y = 0.0):
self.x = float(x)
self.y = float(y)
#property
def x(self):
return self._x
#x.setter
def x(self, value):
self._x = value
#property
def y(self):
return self._y
#y.setter
def y(self, value):
self._y = value
def dist(self, secondPoint):
#get the self x values from self.x and the values
#of the seecond point from secondPoint.x
#same with y
dist = math.sqrt(((self.x - secondPoint.x)**2)+ ((self.y - secondPoint.y)**2))
return dist
def midpt(self, secondPoint):
#same as the dist
midpointx = (self.x + secondPoint.x)/2
midpointy = (self.y + secondPoint.y)/2
midpoint = Point(midpointx,midpointy)
return midpoint
def __str__(self):
return "({},{})".format(self.x,self.y)
I hope this also helps clarify things. I don't have the Canvas class because it is a part of Tkinter.
You used def instead of class for SierpinskiTriangle which means it only takes one argument (Fractal) instead of treating Fractal as its super class.
Change that to class like below and it will take 4 arguments.
class SierpinskiTriangle(Fractal):
def __init__(self, dimensions, num_points, ratio, vertices):
Fractal.__init__(self, dimensions, num_points, ratio, vertices)
class Square():
def __init__(self, side):
self.side = side
def getArea(self):
return side*side
def getAreaOfAllInstances(self):
{need to write this method}
s1 = Square(2)
s2 = Square(3)
print(s1.getAreaOfAllInstances()) ===> This should print 13 (2*2 + 3*3)
print(s2.getAreaOfAllInstances()) ===> This should print 13 (2*2 + 3*3)`
You can use class variable:
class Square():
squares = []
def __init__(self, side):
self.side = side
self.squares.append(self)
def getArea(self):
return self.side * self.side
def getAreaOfAllInstances(self):
return sum(s.getArea() for s in self.squares)
s1 = Square(2)
s2 = Square(3)
print(s1.getAreaOfAllInstances()) #===> This should print 13 (2*2 + 3*3)
print(s2.getAreaOfAllInstances()) # ===> This should print 13 (2*2 + 3*3)
But that's not a clean solution. I'd rather create another class, to keep track of Squares. Like this:
class Square:
def __init__(self, side):
self.side = side
def getArea(self):
return self.side * self.side
class SquareContainer:
def __init__(self):
self.squares = []
def create_square(self, side):
square = Square(side)
self.squares.append(square)
return square
def getAreaOfAllInstances(self):
return sum(s.getArea() for s in self.squares)
sc = SquareContainer()
s1 = sc.create_square(2)
s2 = sc.create_square(3)
print(sc.getAreaOfAllInstances())
Sure you can:
class Square():
_all_instances = []
def __init__(self, side):
self.side = side
self._all_instances.append(self)
def getArea(self):
return side*side
#classmethod
def getAreaOfAllInstances(cls):
return sum(inst.getArea() for inst in cls._all_instances)
Note however that this means that Squares will never be gargabe collected, except if you empty the Square._all_instances attribute.
You can use classmethods to achieve this.
class Square(object):
instances_list = [] # Property of the class
def __init__(self, side):
self.trackInstances(self)
self.side = side
def getArea(self):
return self.side**2
#classmethod
def trackInstances(cls, self):
self.instances_list.append(self)
#classmethod
def getAreaOfAllInstances(cls):
areaSum = sum(map(lambda i: i.getArea(), cls.instances_list))
print('square of all instances: {}'.format(areaSum))
s1 = Square(2)
s2 = Square(3)
s2.getAreaOfAllInstances()
Output:
square of all instances: 13
Note that only s2.getAreaOfAllInstances is executed, and it gives the areas of all instances.