In Python, can an object have another object as an attribute? For example, can a class called car have a class called开发者_如何学运维 tire as an attribute?
Do you mean a class tire
or an instance of class tire
? It can have both although the latter is probably more useful. If you're looking for an object of class Mary
to has-a object of type Fred
you'd want the classinst
variety of assignment:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
>>> class Fred(object): pass
...
>>> class Mary(object):
... def __init__(self):
... self.classref = Fred
... self.classinst = Fred()
...
>>> x = Mary()
>>> dir(x)
[... 'classinst', 'classref']
>>> x.classref
<class '__main__.Fred'>
>>> x.classinst
<__main__.Fred object at 0xb76eed0c>
Yes.
>>> class tire:
... pass
...
>>> class car:
... def __init__(self, tire):
... self.tire = tire
...
>>> t = tire()
>>> t.brand = 'Goodyear'
>>> c = car(t)
>>> c.tire.brand
'Goodyear'
You can have both instances and classes as attributes of both classes and instances -- all four combinations work just fine (and can be combined freely). However, do keep in mind the distinction between a class and an instance thereof -- the way you phrase your question suggests some confusion. Anyway, taking your question literally:
can a class called car have a class called tire as an attribute?
class tire(object):
...class body here...
class car(object):
thetire = tire
...rest of class body here...
A tire = tire
assignment in the body of car
would not work (naming confusion!-) so you need to name the class attribute differently than the class that's its value. (This does not apply to instance attributes, since their syntax, e.g. self.tire
, is that of qualified names, not barenames, so there's no naming confusion -- only to class attributes). Was that perchance the source of the problem that led you to ask this question?
Sure; classes, like any other value, can be either class or instance attributes:
class A(object):
pass
class B(object):
class_attr = A
def __init__(self):
self.instance_attr = A
With this code, you could use B.class_attr
or B().instance_attr
to access A
.
精彩评论