Python Forum
How to call a class in other class?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to call a class in other class?
#1
Hi! I have a problem in which a farmer want to calculate the area of a land when he buying a new land and to add at the existing one.
The shape of land are different, I reduce the shape at 3: circle, square and right angle.

I made a class for every shape
import math

class Circle:
    def __init__(self,radius):
        self.radius = radius
    
    def area_circle(self):
        return math.pi*(self.radius**2)

class Square:
    def __init__(self, side):
        self.side = side

    def area_square(self):
        return self.latura**2

class RightAngle:
    def __init__(self, width, length):
        self.width = width
        self.length = length
    
    def area_right_angle(self):
        return self.length * self.width
Can you help me to create the class farmer, I don't know how tie that 3 class with farmer class.

And extra if doesn't have a exactly form how should I do it? This part for me know is not very important, more important is the first part.
Thanks!
Reply
#2
Probably your farmer class will have a name, age, gender, experience points, and so on data and some methods.

You could have a dictionary data field to keep all farmland your farm owns.

And when your farmboy or girl buys farmland you create a new object from the class Square.
You could pick a name for that parcel because you will have a few of the same shapes and use it as a key in that dict and the object ( you just created ) as a value

I don't do much object-oriented programming. One could give you a different way to store that data. But this is a straight approach.

Just create the object
class Farmer:
    # class data
    self.farmland = {}
    # some class methods

    def new_farmland(self, name):
        new_farmland = Square()
        self.farmland[name] = new_farmland
Now you can change the area methods to be the same name so you can get all the area the farmer owns within a loop.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Your shapes should probably have a common superclass, Shape, that defines the things that shapes can do, like add (+) and __str__. All shapes should have an area attribute, and the area attribute should have the same name for each shape. Getting the area of a circle or a square should look identical from outside the class. You should be able to treat shapes generically without having to know what kind of shape they are.

Why do you need a class for the farmer? Are there many farmers you need to keep track of? You might make a Land class that is a collection of shapes, but I see no need for a farmer class. If your shapes are designed well you don't really need a special Land class either. A list should be enough. I envision defining a farmer's land to look like this:
land = [Circle(5), Square(7), Rectangle(6, 5)]
land.extend([Triangle(11, 7), Shape(33)]
print("Sum", sum(land))
print("\n".join(map(str, land)))
Output:
Sum 229.03981633974485 Circle(area=78.53981633974483, radius=5) Square(area=49, side=7) Rectangle(area=30, wide=6, high=5) Triangle(area=38.5, base=11, high=7) Shape(area=33)
Now all you have to do is write all the shapes. The base class should do most of the work, and the Circle, Square, etc classes should only do things specific to their shape (calculate area). My Shape base class implements __init__, __str__, __add__ and __radd__. __str__ makes it easy to print the shapes. __add__ lets me do thing like print(Circle(5) + Square(5)). __radd__ lets you do things like sum(list_of_shapes).

I decided against making Shape an abstract base class (ABC) so it can be used to represent shapes that are not circles, squares, rectangles or triangles.

Depending on your needs you could also implement __eq__ and __gt__ in your base class to support comparing shape areas or sorting lists of shapes by their area.

That lets you do things like this:
def square_a_shape(shape, step=0.0001):
    """This is a silly way to square a shape."""
    square = Square(0)
    while square < shape:
        square.side += step
    return square

circle = Circle(10)
square = square_a_shape(circle)
print(circle, square)
Output:
Circle(area=314.1592653589793, radius=10) Square(area=314.157900250188, side=17.724500000005303)
Reply
#4
Hi, to call a class in other class there are a few options:

  • Use an instance of A to call method1 (using two possible forms).

  • Apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.

  • Apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How does this code create a class? Pedroski55 6 430 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  class definition and problem with a method HerrAyas 2 267 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  Printing out incidence values for Class Object SquderDragon 3 303 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  class and runtime akbarza 4 393 Mar-16-2024, 01:32 PM
Last Post: deanhystad
  Operation result class SirDonkey 6 563 Feb-25-2024, 10:53 AM
Last Post: Gribouillis
  The function of double underscore back and front in a class function name? Pedroski55 9 679 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  super() and order of running method in class inheritance akbarza 7 765 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Class test : good way to split methods into several files paul18fr 4 487 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  Good class design - with a Snake game as an example bear 1 1,845 Jan-24-2024, 08:36 AM
Last Post: annakenna
  question about __repr__ in a class akbarza 4 618 Jan-12-2024, 11:22 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020