Tash
Tash

Reputation: 59

How do you call different class using a class?

i am learning about object oriented programming in a python and i am trying to write a program which calls class B as a variable to class A. May i know if my approach of handling this correct?

Example of class A

Class A():
   _name = str
   _cost = int

   def __init__(self, _name, _cost):
       self.name = _name
       self.cost = _cost
   def name(self):
       return self.name
   def cost(self):
       return self.cost

Example of class B

Class B():
   _a = A
   def __init__(self,_a):
      self.a = _a
   def __str__(self):
      return 'Phone Model: ', a.name, 'Cost: ', a.cost
phone= B('phone_X', 100)
print(phone.__str__())

Thank you in advance!

Upvotes: 1

Views: 147

Answers (2)

chepner
chepner

Reputation: 530872

The kinds of things you are currently trying to do in A (declare the existence and type of each instance variable) is something that the dataclasses module supports starting in Python 3.7.

from dataclasses import dataclass

@dataclass
class A():
   name: str
   cost: int

There is no need in Python to define a method that does nothing but return the value of an instance attribute; just access the attribute directly.

@dataclass
class B():
    _a: A

    def __str__(self):
        return f'Phone Model: {self._a.name}, Cost: {self._a.cost}'

Now you can pass an explicitly defined instance of A as the argument to B, then pass the instance of B to str in order to get a string value.

phone = B(A('phone_X', 100))
print(str(phone))

Upvotes: 0

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

This should do it. Note that I simplified the logic of class A and B.

class A():

    # name and cost are constructor arguments
    def __init__(self, name, cost):
       self.name = name
       self.cost = cost

We have removed _name and _cost is because we want to assign values to name and cost when we call a new instance of class A, which is done in the __init__. So when you want to create an instance of class A, you would assign values like this: product = A("phoneX",5). Now you have an instance of class A called "product" which has name = "phoneX" and cost = 5.

class B():

    # Passing object of A as an argument
    def __init__(self, a):

      self.a = a

    # This function should return a string
    def __str__(self):
        return 'Phone Model: '+ self.a.name+ ' Cost: '+ str(self.a.cost)

# Instantiating object of A and passing it to B
a = A('phone_X', 100)
phone= B(a)
# Just printing the object would suffice
print(phone)
# Phone Model: phone_X Cost: 100

We have removed _a for the same reasons we removed the _name and _cost variables in class A. In the __init__ for this class, you are assuming that the variable 'a' is going to be an instance of class A. So it will have a name and cost variable.

Upvotes: 3

Related Questions