user17203516
user17203516

Reputation:

Use object from one class as attribute for another class

I am trying to make a circle which asks only for a center and radius. Here is my code:

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def print_point(self):
        print(f"Point: {self.x, self.y}")


class Circle:

    def __init__(self, center, radius):
        self.center = center
        self.radius = radius

    def print_circle(self):
        print(f"Circle: {(self.center), self.radius}")


p1 = Point(150, 100)
c1 = Circle(p1, 75)
c1.print_circle()

What am I doing wrong?

Upvotes: 0

Views: 1504

Answers (2)

Fra93
Fra93

Reputation: 2082

You can assign the __repr__ method to your point class:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point: {self.x, self.y}"


class Circle:
    def __init__(self, center, radius):
        self.center = center
        self.radius = radius

    def print_circle(self):
        print(f"Circle: {((self.center)), self.radius}")

p1 = Point(150, 100)
c1 = Circle(p1, 75)
c1.print_circle()

Upvotes: 2

Jackson V
Jackson V

Reputation: 76

It looks like you're not actually getting any info from the class that's being passed, and just trying to print the object itself. I haven't tested this code myself but try

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def print_point(self):
        print(f"Point: {self.x, self.y}")


class Circle:
    def __init__(self, center, radius):
        self.center = center
        self.radius = radius

    def print_circle(self):
        print(f"Circle: {((self.center.x),(self.center.y)), self.radius}")

p1 = Point(150, 100)
c1 = Circle(p1, 75)
c1.print_circle()

or use another function that returns the string to be printed:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def print_point(self):
        print(f"Point: {self.x, self.y}")
    
    def get_point(self):
        return f'Point: {self.x, self.y}'


class Circle:
    def __init__(self, center, radius):
        self.center = center
        self.radius = radius

    def print_circle(self):
        print(f"Circle: {self.center.get_point()},{self.radius}")

p1 = Point(150, 100)
c1 = Circle(p1, 75)
c1.print_circle()

Upvotes: 0

Related Questions