Reputation: 461
I'm new to python and I would like to know if this is possible or not:
I want to create an object and attach to it another object.
OBJECT A
Child 1
Child 2
OBJECT B
Child 3
Child 4
Child 5
Child 6
Child 7
is this possible ?
Upvotes: 1
Views: 83
Reputation: 7952
To follow your example:
class Car(object):
def __init__(self, tire_size = 1):
self.tires = [Tire(tire_size) for _ in range(4)]
class Tire(object):
def __init__(self, size):
self.weight = 2.25 * size
Now you can make a car and query the tire weights:
>>> red = Car(1)
>>> red.tires
[<Tire object at 0x7fe08ac7d890>, <Tire object at 0x7fe08ac7d9d0>, <Tire object at 0x7fe08ac7d7d0>, <Tire object at 0x7fe08ac7d950>]
>>> red.tires[0]
<Tire object at 0x7fe08ac7d890>
>>> red.tires[0].weight
2.25
You can change the structure as needed, as a better way (if all the tires are the same) is to just specify tire
and num_tires
:
>>> class Car(object):
def __init__(self, tire):
self.tire = tire
self.num_tires = 4
>>> blue = Car(Tire(2))
>>> blue.tire.weight
4.5
>>> blue.num_tires
4
Upvotes: 1
Reputation: 35
Here is an example:
In this scenario an object can be a person without being an employee, however to be an employee they must be a person. Therefor the person class is a parent to the employee
Here's the link to an article that really helped me understand inheritance: http://www.python-course.eu/python3_inheritance.php
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(self,first, last)
self.staffnumber = staffnum
def GetEmployee(self):
return self.Name() + ", " + self.staffnumber
x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")
print(x.Name())
print(y.GetEmployee())
Upvotes: 0
Reputation: 3514
If you are talking about object oriented terms, yes you can,you dont explain clearly what you want to do, but the 2 things that come to my mind if you are talking about OOP are:
Upvotes: 4