简体   繁体   中英

Child and parent object

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 ?

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:

  • If you are talking about inheritance you can make child objects extend parent objects when you create your child class: class child(parent):
  • If you are talking about object composition, you just make child object an isntance variable of parent object and pass it as a constructor variable

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

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM