我是python的新手,我想知道这是否可行:
我想创建一个对象并将另一个对象附加到它上面。
OBJECT A
Child 1
Child 2
OBJECT B
Child 3
Child 4
Child 5
Child 6
Child 7
这可能吗?
答案 0 :(得分:4)
如果你在谈论面向对象的术语,是的,你可以,你不清楚你要做什么,但如果你在谈论OOP,我想到的两件事是:
答案 1 :(得分:1)
按照你的例子:
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
现在你可以开车并查询轮胎重量:
>>> 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
您可以根据需要更改结构,更好的方法(如果所有轮胎都相同)只需指定tire
和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
答案 2 :(得分:0)
以下是一个例子:
在这种情况下,对象可以是不是雇员的人,但是作为雇员,他们必须是一个人。因此,person类是员工的父母
这是一篇真正帮助我理解继承的文章的链接: 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())