将类的实例传递给另一个类
我不太明白的是 b = Bar(a)
这行代码到底在干嘛?Bar
是怎么把 a
当作参数来用的呢?
这是不是意味着 Bar
是从 a
继承来的?还有 Bar.Foo1 = Foo
这句是什么意思?是不是说 Foo1
是 Foo()
这个类的一个实例?那我们要怎么访问 Foo1
呢?它本身不就是一个对象吗?再说 b.arg.variable
这部分,难道不是说 b
有一个叫 arg
的方法,而这个方法里有个变量叫 variable
吗?下面的代码来自于 这个回答
我就是找不到把对象作为参数传给另一个类的用法。
class Foo (object):
#^class name #^ inherits from object
bar = "Bar" #Class attribute.
def __init__(self):
# #^ The first variable is the class instance in methods.
# # This is called "self" by convention, but could be any name you want.
self.variable="Foo" #instance attribute.
print self.variable, self.bar #<---self.bar references class attribute
self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
print self.variable, self.bar
def method(self,arg1,arg2):
#This method has arguments. You would call it like this : instance.method(1,2)
print "in method (args):",arg1,arg2
print "in method (attributes):", self.variable, self.bar
a=Foo() # this calls __init__ (indirectly), output:
# Foo bar
# Foo Bar is now Baz
print a.variable # Foo
a.variable="bar"
a.method(1,2) # output:
# in method (args): 1 2
# in method (attributes): bar Bar is now Baz
Foo.method(a,1,2) #<--- Same as a.method(1,2). This makes it a little more explicit what the argument "self" actually is.
class Bar(object):
def __init__(self,arg):
self.arg=arg
self.Foo1=Foo()
b=Bar(a)
b.arg.variable="something"
print a.variable # something
print b.Foo1.variable # Foo
2 个回答
这里有一个更简单的例子。假设你有这些类:
class Foo(object):
pass
class Bar(object):
def __init__(self, arg):
self.arg = arg
你可以做两件事情:
# Option 1: pass in an integer
>>> b = Bar(1)
>>> b.arg
1
# Option 2: pass in a Foo object
>>> a = Foo()
>>> b = Bar(a)
>>> b.arg
<__main__.Foo object at 0x0000000002A440F0>
这两种情况的处理方式是完全一样的。传入a
(一个Foo对象)和传入一个整数没有任何区别。Bar
所做的就是存储传入的值,无论是Foo对象还是整数,它都能一样存储。当你调用Bar(something)
时,Bar
类决定如何处理传入的对象。传入对象的类型并不影响处理方式,除非Bar
选择明确地使用它(比如,通过调用传入对象的方法)。
我不太明白的是 b = Bar(a)
这句代码到底在干嘛?
b = Bar(a)
做了两件事。首先,它创建了一个 Bar
类的对象(这个对象会有一些类变量和方法)。然后,它会运行 __init__
方法,传入的第一个参数(self
)指向刚刚创建的对象,第二个参数是 a
(也就是 arg
)。在运行 __init__
的过程中,其中一个命令会把 self.arg
设置为指向 arg
指向的对象(也就是 a
变量指向的对象)。最后,变量 b
被设置为指向这个新创建的对象。
可以这样理解:在 Python 中,变量其实就是指向对象的指针。你可以有多个变量指向同一个对象。在这个例子中,a
和 b.arg
都指向同一个对象。
我一开始也觉得这很 confusing。我曾经看到有人建议把变量和它指向的对象看作是两个不同的概念,但我觉得这样太复杂了,后来我不得不回过头来接受这种思维方式,才能理解这些内容。人们常常用变量的名字来指代它所指向的对象;你只需要知道什么时候要字面理解,什么时候不需要。
“那不是意味着 Bar 会继承 a 吗?”
不是的。如果 a
是一个类,那么 class Bar(a)
就意味着 Bar 继承自 a
。但是在 b = Bar(a)
中,a
是作为参数传递给 __init__
的一个对象。
“Bar.Foo1 = Foo
是什么意思?”
抱歉,我在你给的示例代码中没有看到这个。
“b.arg.variable
的意思是什么?”
b
是一个对象(也就是说,b
指向一个对象),而 b.arg
是这个对象的一个属性。方法和变量是不同类型的属性。在这个例子中,b.arg
是一个指向对象的变量。b.arg
指向的对象有一个属性 variable
,这个属性也是一个变量。
b.arg
指向的对象和 a
指向的对象是一样的,因此 b.arg.variable
和 a.variable
是同一个变量。它不仅指向同一个对象,实际上就是同一个变量。它指向的对象是字符串 "something"
。
@Brenbarn: 我觉得这就是 quirius 所说的“那不是意味着 Bar 会继承 a 吗?”的意思。